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 {
  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";

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

    const updatedSummary = {
      ...baseCollectingCostSummary,
      actualMaterialCost: 2100,
    };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [baseCollectingCostSummary],
      [], // no duplicate
      [{}],
      [updatedSummary],
    );

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

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

  it("returns error when the production order 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(ProductionOrderNotFoundError);
    }
  });

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

    mock.enqueueResults([baseReleasedProductionOrder], []);

    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 collecting", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseReleasedProductionOrder], [basePendingReviewCostSummary]);

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

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

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

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

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

    mock.enqueueResults([baseReleasedProductionOrder], [baseCollectingCostSummary]);

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

    mock.enqueueResults([baseReleasedProductionOrder], [baseCollectingCostSummary], [baseCostLine]);

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

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