import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import type { WorkflowItem } from '@application/queries/GetWorkflows';

export interface UpdateWorkflowCommand {
  type: 'update-workflow';
  workflowId: number;
  materialIdx?: number;
  stepIdx?: number;
  crossingIdx?: number;
  done: number;
}

export function createUpdateWorkflowHandler(state: AppState, repo: StateRepository) {
  return (cmd: UpdateWorkflowCommand): void => {
    const workflows = state.workflows as WorkflowItem[];
    const wf = workflows.find(w => w.id === cmd.workflowId);
    if (!wf) return;

    if (cmd.materialIdx !== undefined) {
      const mat = wf.materials[cmd.materialIdx];
      if (mat) mat.done = Math.max(0, cmd.done);
    } else if (cmd.stepIdx !== undefined && cmd.crossingIdx !== undefined) {
      const step = wf.steps[cmd.stepIdx];
      if (step) {
        const crossing = step.crossings[cmd.crossingIdx];
        if (crossing) crossing.done = Math.max(0, cmd.done);
      }
    }

    repo.save(state);
  };
}
