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 {
  EmptyReceiptLinesError,
  InvalidUnitConversionRateError,
  InvalidQuantityError,
  InvalidUnitCostError,
  ItemNotFoundError,
  PrimaryUnitMismatchError,
} from "../lib/errors.generated";
import { expectErr, expectOk, mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseGoodsReceiptExecution,
  baseGoodsReceiptExecutionLine,
  baseInactiveItem,
  baseInactiveLocation,
  baseStorageLocation,
} from "../testing/fixtures";
import { run } from "./createGoodsReceipt";

describe("createGoodsReceipt", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory:inventoryOperation:createGoodsReceipt"],
  };
  const header = {
    effectiveDate: new Date("2024-01-10T00:00:00.000Z"),
    sourceDocumentType: "PURCHASE_ORDER" as const,
    sourceDocumentId: "po-1",
  };
  const receiptLine = {
    itemId: "item-1",
    storageLocationId: "location-1",
    quantity: "5",
    unitId: "unit-box",
    primaryQuantity: "10",
    primaryUnitId: baseActiveItem.unitId,
    unitConversionRate: "2",
  };

  it("returns error when no lines are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(trx, { header, lines: [] }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expectErr(result as never, EmptyReceiptLinesError);
  });

  it("returns error when line quantity is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, quantity: "0" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidQuantityError);
  });

  it("returns error when line primary quantity is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, primaryQuantity: "0" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidQuantityError);
  });

  it("returns error when line unit conversion rate is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, unitConversionRate: "0" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidUnitConversionRateError);
  });

  it("returns error when line unit cost is negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, unitCost: "-1" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidUnitCostError);
  });

  it("returns error when item does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, itemId: "missing" }],
        },
        ctx,
        mockItemManagementQueries(null),
      ),
    );

    expectErr(result as never, ItemNotFoundError);
  });

  it("returns error when primary unit differs from item primary unit", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, primaryUnitId: "unit-kg" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, PrimaryUnitMismatchError);
  });

  it("creates a DRAFT goods receipt execution with inbound lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStorageLocation],
      [baseGoodsReceiptExecution],
      [baseGoodsReceiptExecutionLine],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [{ ...receiptLine, unitCost: "12", sourceLineId: "po-line-1" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    const value = expectOk<{ inventoryExecution: { status: string; executionType: string } }>(
      result as never,
    );

    expect(value.inventoryExecution).toMatchObject({
      executionType: "GOODS_RECEIPT",
      status: "DRAFT",
    });
    expect(mock.inserts[1].insertRows()).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          direction: "IN",
          quantity: "5",
          unitId: "unit-box",
          primaryQuantity: "10",
          primaryUnitId: receiptLine.primaryUnitId,
          unitConversionRate: "2",
          unitCost: "12",
          stockType: "AVAILABLE",
        }),
      ]),
    );
  });

  it("accepts inactive item and location references", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseInactiveLocation],
      [baseGoodsReceiptExecution],
      [baseGoodsReceiptExecutionLine],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header,
          lines: [
            {
              ...receiptLine,
              itemId: "item-3",
              storageLocationId: "location-3",
            },
          ],
        },
        ctx,
        mockItemManagementQueries(baseInactiveItem),
      ),
    );

    const value = expectOk<{ inventoryExecution: { status: string } }>(result as never);

    expect(value.inventoryExecution.status).toBe("DRAFT");
  });
});
