import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CostSummaryNotFoundError,
  CostSummaryNotSettlableError,
  AcknowledgmentMismatchError,
  AcknowledgmentRejectedOrSupersededError,
  AcknowledgmentSourceInvalidError,
} from "../lib/errors.generated";
import { baseReviewedCostSummary, basePendingReviewCostSummary } from "../testing/fixtures";
import { run } from "./recordManufacturingCostSettlementAcknowledgment";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("recordManufacturingCostSettlementAcknowledgment", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing:recordManufacturingCostSettlementAcknowledgment"],
  };

  const validInput = {
    costSummaryId: "cost-summary-3",
    productionOrderId: "production-order-2",
    currencyCode: "USD",
    settlementReference: "SETTLE-2024-001",
    settlementDate: "2024-04-15",
    acknowledgedDate: "2024-04-15",
    acknowledgmentStatus: "ACCEPTED",
    acknowledgmentSource: "downstream-accounting-system",
  };

  it("records a valid downstream settlement acknowledgment and settles the summary", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseReviewedCostSummary);

    const settledSummary = {
      ...baseReviewedCostSummary,
      status: "SETTLED",
    };
    spies.insert.mockReturnValue({});
    spies.update.mockReturnValue(settledSummary);

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.manufacturingCostSummary.status).toBe("SETTLED");
    }
    expect(spies.insert).toHaveBeenCalled();
    expect(spies.update).toHaveBeenCalled();
  });

  it("returns error when the summary does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CostSummaryNotFoundError);
    }
  });

  it("returns error when the summary is not variance reviewed", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(basePendingReviewCostSummary); // PENDING_VARIANCE_REVIEW

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CostSummaryNotSettlableError);
    }
  });

  it("returns error when the payload does not match the reviewed handoff", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseReviewedCostSummary);

    const result = await run(
      db,
      { ...validInput, currencyCode: "EUR" }, // mismatch
      ctx,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AcknowledgmentMismatchError);
    }
  });

  it("returns error when downstream accounting rejects, reverses, or supersedes the reviewed handoff", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseReviewedCostSummary);

    const result = await run(db, { ...validInput, acknowledgmentStatus: "REJECTED" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AcknowledgmentRejectedOrSupersededError);
    }
  });

  it("returns error when the acknowledgment source is invalid", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { ...validInput, acknowledgmentSource: null }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AcknowledgmentSourceInvalidError);
    }
  });
});
