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

export interface SaveWorkflowCommand {
  type: 'save-workflow';
  target: string;
  qty: number;
  materials: { race: string; m: number; f: number }[];
  steps: { baby: string; parentA: string; parentB: string; couples: number; gen: number }[];
  repro: Record<string, number>;
}

export function createSaveWorkflowHandler(state: AppState, repo: StateRepository) {
  return (cmd: SaveWorkflowCommand): void => {
    const workflows = state.workflows as WorkflowItem[];

    // Group steps by gen (already sorted gen2 → genN after calcAppro reverse)
    const genMap = new Map<number, typeof cmd.steps>();
    for (const step of cmd.steps) {
      if (!genMap.has(step.gen)) genMap.set(step.gen, []);
      genMap.get(step.gen)!.push(step);
    }

    const wfSteps = Array.from(genMap.entries())
      .sort(([a], [b]) => a - b)
      .map(([gen, steps]) => ({
        gen,
        crossings: steps.map(s => ({
          race: s.baby,
          needed: s.couples,
          parentA: s.parentA,
          parentB: s.parentB,
          couples: s.couples,
          repro: cmd.repro[s.baby] ?? 0,
          done: 0,
        })),
      }));

    const wf: WorkflowItem = {
      id: Date.now(),
      name: `${cmd.target} ×${cmd.qty}`,
      target: cmd.target,
      qty: cmd.qty,
      createdAt: Date.now(),
      materials: cmd.materials.map(m => ({
        name: m.race,
        needed: m.m + m.f,
        done: 0,
      })),
      steps: wfSteps,
    };

    workflows.push(wf);
    repo.save(state);
  };
}
