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

describe("recordManufacturingCostSettlementAcknowledgment", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing: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 mock = createKyselyMock<Namespace["main-db"]>();

    const settledSummary = {
      ...baseReviewedCostSummary,
      status: "SETTLED",
    };

    mock.enqueueResults([baseReviewedCostSummary], [{}], [settledSummary]);

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.manufacturingCostSummary.status).toBe("SETTLED");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when the summary does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([basePendingReviewCostSummary]); // PENDING_VARIANCE_REVIEW

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseReviewedCostSummary]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseReviewedCostSummary]);

    const result = await mock.withTx((trx) =>
      run(trx, { ...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 mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, { ...validInput, acknowledgmentSource: null }, ctx),
    );

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