import { describe, expect, it } from "vitest";
import { buildM7Dataset, computeM3Counters } from "@/lib/compliance/m7";
import { ProposalWorkflowStateSchema } from "@/lib/proposals/workflow-state";

function buildWorkflow(overrides?: Partial<ReturnType<typeof ProposalWorkflowStateSchema.parse>>) {
  const base = ProposalWorkflowStateSchema.parse({
    step: 5,
    info: {
      title: "Proceso de prueba",
      issuingEntity: "Entidad",
      procedureType: "Publica",
      jurisdiction: "Estatal",
      state: "Nuevo Leon",
      municipality: "Monterrey",
      sector: "Tecnologia",
      description: "Servicio",
      convocatoriaUrl: "https://example.com",
    },
    requirements: [
      {
        id: "req-1",
        title: "Requisito critico",
        description: "Debe cumplirse",
        category: "legal",
        mandatory: true,
        source: "critical_requirement",
        status: "pending",
        note: "",
        evidences: [],
      },
    ],
    technicalSections: [
      {
        id: "tech-1",
        title: "Tecnica",
        description: "Seccion",
        completed: true,
      },
    ],
    economicItems: [
      {
        id: "eco-1",
        concept: "Concepto",
        unit: "pieza",
        quantity: 1,
        unitPrice: 100,
      },
    ],
    milestones: [
      {
        id: "mil-1",
        title: "Entrega",
        dateIso: "2026-04-03T10:00:00.000Z",
        location: "",
        note: "",
        source: "manual",
      },
    ],
    signatureCompliance: {
      policyStatus: "requiere_validacion_legal",
      policyName: "Politica",
      jurisdictionLabel: "Nuevo Leon",
      sourceUrl: "",
      minimumEvidence: ["Opinion legal"],
      notes: "",
      validatedByLegal: false,
    },
    readyMarked: false,
  });

  return {
    ...base,
    ...(overrides ?? {}),
  };
}

describe("buildM7Dataset", () => {
  it("computes KPIs and tabs using M3+M5 inputs", () => {
    const now = new Date("2026-04-02T10:00:00.000Z");
    const m3 = computeM3Counters({
      totalOpenLicitations: 10,
      preferences: [{ status: "REVIEWED" }, { status: "INTERESTED" }],
      activeLinked: 2,
    });

    const dataset = buildM7Dataset({
      proposals: [
        {
          id: "p-1",
          title: "Propuesta activa",
          status: "IN_PROGRESS",
          sourceLicitationId: "l-1",
          workflowDraft: buildWorkflow(),
          updatedAt: now,
        },
        {
          id: "p-2",
          title: "Archivada",
          status: "ARCHIVED",
          sourceLicitationId: "l-2",
          workflowDraft: buildWorkflow(),
          updatedAt: now,
        },
      ],
      m3,
      dueVerifications: [
        {
          sourceId: "nl-1",
          sourceTitle: "Reglamento NL",
          authorityName: "Gobierno NL",
          dueAt: "2026-04-04T09:00:00.000Z",
          overdue: false,
        },
      ],
      now,
    });

    expect(dataset.kpis.activeLicitations).toBe(1);
    expect(dataset.kpis.upcoming7Days).toBeGreaterThanOrEqual(2);
    expect(dataset.kpis.criticalPending).toBeGreaterThan(0);
    expect(dataset.m3States.consulted).toBe(1);
    expect(dataset.m3States.interested).toBe(1);
  });
});
