import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  CostSummaryNotFoundError,
  CostSummaryNotCollectingError,
  MissingInventoryIssueReferenceError,
  MissingActualUnitCostError,
  MissingActualExtendedCostError,
  MissingPostingDateError,
  IssueOutcomeNotFinalError,
  DuplicateIssueOutcomeError,
} from "../lib/errors.generated";
import {
  baseReleasedProductionOrder,
  baseCollectingCostSummary,
  basePendingReviewCostSummary,
  baseCostLine,
} from "../testing/fixtures";
import { run } from "./recordInventoryIssueOutcome";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const validInput = {
    productionOrderId: "production-order-2",
    inventoryIssueReference: "INV-ISSUE-001",
    itemReference: "item-2",
    issuedQuantity: 200,
    unitOfMeasure: "EA",
    actualUnitCost: 10.5,
    actualExtendedCost: 2100,
    currency: "USD",
    valuationMethod: "STANDARD",
    postingDate: "2024-03-10",
    siteReference: "site-1",
    isFinalValuation: true,
  };

  it("applies a final-valued inventory issue outcome to a collecting summary", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // select: production order, cost summary, existing cost line (duplicate check)
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);
    spies.select.mockReturnValueOnce(undefined); // no duplicate

    const updatedSummary = {
      ...baseCollectingCostSummary,
      actualMaterialCost: 2100,
    };
    spies.insert.mockReturnValue({});
    spies.update.mockReturnValue(updatedSummary);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.manufacturingCostSummary).toEqual(updatedSummary);
    }
    expect(spies.insert).toHaveBeenCalled();
    expect(spies.update).toHaveBeenCalled();
  });

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

    spies.select.mockReturnValueOnce(undefined); // no production order

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

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

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

    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    spies.select.mockReturnValueOnce(undefined); // no cost summary

    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 collecting", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    spies.select.mockReturnValueOnce(basePendingReviewCostSummary); // not COLLECTING

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

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

  it("returns error when inventoryIssueReference is missing from the outcome payload", async () => {
    const { db } = createMockDb<Transaction>();

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

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

  it("returns error when actualUnitCost is missing from the outcome payload", async () => {
    const { db } = createMockDb<Transaction>();

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

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

  it("returns error when actualExtendedCost is missing from the outcome payload", async () => {
    const { db } = createMockDb<Transaction>();

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

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

  it("returns error when postingDate is missing from the outcome payload", async () => {
    const { db } = createMockDb<Transaction>();

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

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

  it("returns error when the inventory issue outcome is not yet final", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);

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

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

  it("returns error when the same issue outcome is applied twice", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);
    spies.select.mockReturnValueOnce(baseCostLine); // duplicate found

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

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