import { beforeEach, describe, expect, it, vi } from "vitest";

const { prismaMock, getM7DatasetForUserMock } = vi.hoisted(() => ({
  prismaMock: {
    proposal: {
      findMany: vi.fn(),
    },
    contractRecord: {
      findMany: vi.fn(),
    },
    legalCase: {
      findMany: vi.fn(),
    },
  },
  getM7DatasetForUserMock: vi.fn(),
}));

vi.mock("@/lib/prisma", () => ({
  prisma: prismaMock,
}));

vi.mock("@/lib/compliance/server", () => ({
  getM7DatasetForUser: getM7DatasetForUserMock,
}));

import { buildInstitutionalDossier } from "@/lib/audits/server";

describe("M4 -> M5 -> M8 -> M9 -> M10 continuity integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("preserves document lineage and module links in M10 dossier payload", async () => {
    const createdAt = new Date("2026-04-15T10:00:00.000Z");

    prismaMock.proposal.findMany.mockResolvedValue([
      {
        id: "proposal-1",
        title: "Propuesta Integral",
        status: "IN_PROGRESS",
        sourceLicitationId: "licit-1",
        documents: [
          {
            id: "proposal-doc-1",
            fileName: "propuesta.pdf",
            mimeType: "application/pdf",
            sizeBytes: 101,
            createdAt,
          },
        ],
      },
    ]);

    prismaMock.contractRecord.findMany.mockResolvedValue([
      {
        id: "contract-1",
        title: "Contrato Marco",
        status: "ACTIVE",
        sourceProposal: {
          id: "proposal-1",
          title: "Propuesta Integral",
        },
        deliverables: [{ id: "del-1" }],
        payments: [{ id: "pay-1" }],
        documents: [
          {
            id: "contract-doc-1",
            fileName: "contrato-firmado.pdf",
            mimeType: "application/pdf",
            sizeBytes: 202,
            kind: "SIGNED_CONTRACT",
            createdAt,
          },
        ],
      },
    ]);

    prismaMock.legalCase.findMany.mockResolvedValue([
      {
        id: "legal-1",
        caseType: "CONTRACT_BREACH",
        severity: "HIGH",
        status: "OPEN",
        contractId: "contract-1",
        documents: [
          {
            id: "legal-doc-1",
            title: "Escrito inicial",
            templateKey: "general_delivery_record",
            createdAt,
          },
        ],
      },
    ]);

    getM7DatasetForUserMock.mockResolvedValue({
      tabs: {
        alertas: [{ severity: "high" }, { severity: "medium" }],
      },
    });

    const dossier = await buildInstitutionalDossier("user-1");

    expect(dossier.summary.proposals).toBe(1);
    expect(dossier.summary.contracts).toBe(1);
    expect(dossier.summary.legalCases).toBe(1);
    expect(dossier.summary.highRiskAlerts).toBe(1);

    expect(dossier.proposals[0]?.links.some((link) => link.href === "/licitations/licit-1")).toBe(true);

    expect(dossier.contracts[0]?.links.some((link) => link.href === "/gestion-licitaciones/proposal-1")).toBe(true);
    expect(dossier.contracts[0]?.documentEntries[0]?.traceLabel).toContain("propuesta M5");
    expect(dossier.contracts[0]?.documentEntries[0]?.links.some((link) => link.href === "/api/contracts/contract-1/documents/contract-doc-1")).toBe(true);

    expect(dossier.legal[0]?.links.some((link) => link.href === "/gestion-contratos?contractId=contract-1")).toBe(true);
    expect(dossier.legal[0]?.documentEntries[0]?.traceLabel).toContain("contract-1");
  });
});
