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

const { requireAdminApiUserMock, prismaMock } = vi.hoisted(() => ({
  requireAdminApiUserMock: vi.fn(),
  prismaMock: {
    licitation: {
      findUnique: vi.fn(),
    },
    normativeAnalysisHistory: {
      findFirst: vi.fn(),
      create: vi.fn(),
    },
    proposal: {
      findFirst: vi.fn(),
      update: vi.fn(),
    },
  },
}));

vi.mock("@/lib/auth/admin", () => ({
  requireAdminApiUser: requireAdminApiUserMock,
}));

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

import { POST } from "@/app/api/proposals/[id]/workflow/extract/route";

describe("M4 -> M5 extract continuity regression", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("blocks extraction when proposal has no M4 source and no uploaded PDF", async () => {
    requireAdminApiUserMock.mockResolvedValue({ id: "user-1" });
    prismaMock.proposal.findFirst.mockResolvedValue({
      id: "proposal-1",
      title: "Propuesta sin fuente",
      issuingEntity: "Entidad",
      summary: "Resumen",
      status: "DRAFT",
      sourceLicitationId: null,
      workflowDraft: null,
    });

    const request = new Request("http://localhost/api/proposals/proposal-1/workflow/extract", {
      method: "POST",
      body: new FormData(),
    });

    const response = await POST(request, {
      params: Promise.resolve({ id: "proposal-1" }),
    });
    const payload = (await response.json()) as { error?: string };

    expect(response.status).toBe(400);
    expect(payload.error).toContain("no tiene fuente de licitacion");
    expect(prismaMock.normativeAnalysisHistory.findFirst).not.toHaveBeenCalled();
  });
});
