import { beforeEach, describe, expect, it, vi } from "vitest";
import { PRIORITY1_MANUAL_FOLLOWUP_ERROR_CODE } from "@/modules/priority1/constants";
import { PRIORITY1_MANUAL_FOLLOWUP_MESSAGE } from "@/workers/rpa/priority1/quote-extract";

const { prismaUpdate, runRpa, recordSuccess, closeCircuit } = vi.hoisted(
  () => ({
    prismaUpdate: vi.fn(),
    runRpa: vi.fn(),
    recordSuccess: vi.fn(),
    closeCircuit: vi.fn(),
  }),
);

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

vi.mock("@/workers/rpa/priority1/run-quote", () => ({
  runPriority1QuoteRpa: runRpa,
}));

vi.mock("@/modules/cache/circuit-breaker", () => ({
  isCircuitOpen: vi.fn().mockResolvedValue(false),
  recordRpaFailure: vi.fn(),
  recordRpaSuccess: recordSuccess,
  closeCircuit: closeCircuit,
}));

vi.mock("@/workers/rpa/worker-state", () => ({
  heartbeat: vi.fn(),
  isWorkerPaused: vi.fn().mockResolvedValue(false),
}));

vi.mock("@/modules/metrics/collector", () => ({
  recordPostDone: vi.fn(),
  safeRecord: (fn: () => void) => fn(),
}));

vi.mock("@/modules/pricing/engine", () => ({
  getMarkupRule: vi.fn(),
  applyMarkupToQuotes: vi.fn(),
}));

vi.mock("@/modules/quote/fallback-orchestrator", () => ({
  handleRpaFailure: vi.fn(),
}));

import { processPriority1QuoteJob } from "@/workers/rpa/priority1-job-handler";

const jobData = {
  quoteId: "Q-P1-001",
  requestId: "req-p1",
  customerId: "cust-1",
  cargoHash: "hash-p1",
  input: {
    shipmentType: "ftl" as const,
    originZip: "98101",
    destinationZip: "33101",
    pickupDate: "07/01/2026",
    phoneCountry: "US",
    phone: "2065550100",
    email: "test@example.com",
    commodity: "General Freight",
    weightLb: "5000",
    ftlTrailer: "temperature_controlled" as const,
    tempMinF: "32",
    tempMaxF: "40",
    palletCount: "1",
  },
};

describe("processPriority1QuoteJob", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("persists manual_followup as done with PRIORITY1_MANUAL_FOLLOWUP", async () => {
    runRpa.mockResolvedValue({
      ok: true,
      quotes: [],
      quoteOutcome: "manual_followup",
      message: PRIORITY1_MANUAL_FOLLOWUP_MESSAGE,
    });

    await processPriority1QuoteJob(jobData, "worker-1");

    expect(prismaUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { quoteId: "Q-P1-001" },
        data: expect.objectContaining({
          status: "done",
          errorCode: PRIORITY1_MANUAL_FOLLOWUP_ERROR_CODE,
          errorMessage: PRIORITY1_MANUAL_FOLLOWUP_MESSAGE,
        }),
      }),
    );
    expect(recordSuccess).toHaveBeenCalled();
    expect(closeCircuit).toHaveBeenCalled();
  });
});
