import type { WorkflowMilestoneSeed, WorkflowRequirementSeed, WorkflowTechnicalSectionSeed } from "@/lib/proposals/workflow";
import type { ProposalWorkflowState } from "@/lib/proposals/workflow-state";
import { evaluateSignaturePolicy } from "@/lib/compliance/signature-policy";

function toProcedureTypeLabel(value: string | null | undefined) {
  if (value === "LICITACION_PUBLICA") {
    return "Publica";
  }

  if (value === "INVITACION_RESTRINGIDA") {
    return "Invitacion restringida";
  }

  if (value === "ADJUDICACION_DIRECTA") {
    return "Adjudicacion directa";
  }

  return "Por definir";
}

export function buildDefaultWorkflowDraft(args: {
  proposal: {
    title: string;
    issuingEntity: string;
    summary: string;
    status: "DRAFT" | "IN_PROGRESS" | "SUBMITTED" | "ARCHIVED";
  };
  linkedSource?: {
    title: string;
    description: string | null;
    issuingEntity: string | null;
    procedureType: string | null;
    stateName: string;
    municipalityName: string;
    sourceUrl: string | null;
    milestones: WorkflowMilestoneSeed[];
  } | null;
  requirementSeeds?: WorkflowRequirementSeed[];
  technicalSectionSeeds?: WorkflowTechnicalSectionSeed[];
}): ProposalWorkflowState {
  const requirementSeeds = args.requirementSeeds ?? [];
  const technicalSectionSeeds = args.technicalSectionSeeds ?? [];
  const linkedSource = args.linkedSource ?? null;
  const signaturePolicy = evaluateSignaturePolicy({
    stateName: linkedSource?.stateName ?? null,
    municipalityName: linkedSource?.municipalityName ?? null,
    documentType: "BASES_LICITACION",
  });

  const requirements: ProposalWorkflowState["requirements"] = requirementSeeds.map((seed) => ({
    ...seed,
    status: "pending",
    note: "",
    evidences: [],
  }));

  const technicalSections: ProposalWorkflowState["technicalSections"] =
    technicalSectionSeeds.length > 0
      ? technicalSectionSeeds.map((seed) => ({
          id: seed.id,
          title: seed.title,
          description: seed.description,
          completed: false,
        }))
      : [
          {
            id: "section-default-1",
            title: "Documentacion Legal y Administrativa",
            description: "Completa y valida los formatos requeridos por la convocatoria.",
            completed: false,
          },
          {
            id: "section-default-2",
            title: "Propuesta Tecnica Detallada",
            description: "Describe alcance, metodologia y cumplimiento de especificaciones.",
            completed: false,
          },
          {
            id: "section-default-3",
            title: "Acreditacion de Experiencia y Capacidad Tecnica",
            description: "Integra cartas, certificaciones y evidencia tecnica del equipo.",
            completed: false,
          },
        ];

  return {
    step: 1,
    info: {
      title: args.proposal.title || linkedSource?.title || "",
      issuingEntity: args.proposal.issuingEntity || linkedSource?.issuingEntity || "",
      procedureType: toProcedureTypeLabel(linkedSource?.procedureType),
      jurisdiction: linkedSource ? "Federal / Estatal" : "Por definir",
      state: linkedSource?.stateName ?? "",
      municipality: linkedSource?.municipalityName ?? "",
      sector: "",
      description: linkedSource?.description || args.proposal.summary || "",
      convocatoriaUrl: linkedSource?.sourceUrl ?? "",
    },
    requirements,
    technicalSections,
    economicItems: [],
    milestones: (linkedSource?.milestones ?? []).map((item) => ({
      ...item,
      source: item.source ?? "licitation",
    })),
    signatureCompliance: {
      policyStatus: signaturePolicy.policyStatus,
      policyName: signaturePolicy.policyName,
      jurisdictionLabel: signaturePolicy.jurisdictionLabel,
      sourceUrl: signaturePolicy.sourceUrl ?? "",
      minimumEvidence: signaturePolicy.evidenceRequired,
      notes: signaturePolicy.notes,
      validatedByLegal: false,
    },
    readyMarked: args.proposal.status === "SUBMITTED",
  };
}
