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

export interface ImportWorkflowsCommand {
  type: 'import-workflows';
  workflows: WorkflowItem[];
}

export function createImportWorkflowsHandler(state: AppState, repo: StateRepository) {
  return (cmd: ImportWorkflowsCommand): void => {
    const existing = state.workflows as WorkflowItem[];
    const existingIds = new Set(existing.map(w => w.id));

    for (const wf of cmd.workflows) {
      if (existingIds.has(wf.id)) {
        // Réattribuer un nouvel id pour éviter les doublons
        wf.id = Date.now() + Math.floor(Math.random() * 1000);
      }
      existing.push(wf);
      existingIds.add(wf.id);
    }

    repo.save(state);
  };
}
