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

describe("updateGoodsReceipt", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory:inventoryOperation:updateGoodsReceipt"],
  };
  const postedExecution = {
    ...baseGoodsReceiptExecution,
    id: "execution-posted",
    status: "POSTED" as const,
  };
  const receiptLine = {
    itemId: "item-1",
    storageLocationId: "location-1",
    quantity: "5",
    unitId: "unit-box",
    primaryQuantity: "10",
    primaryUnitId: baseActiveItem.unitId,
    unitConversionRate: "2",
  };

  it("updates header metadata on a draft goods receipt", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = {
      ...baseGoodsReceiptExecution,
      effectiveDate: new Date("2024-02-01T00:00:00.000Z"),
    };
    mock.enqueueResults(
      [baseGoodsReceiptExecution], // InventoryExecution
      [baseGoodsReceiptExecutionLine], // InventoryExecutionLine (current lines)
      [updated], // updateTable InventoryExecution
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: baseGoodsReceiptExecution.id, headerPatch: { effectiveDate: updated.effectiveDate } },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

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

    expect(value.inventoryExecution.effectiveDate).toEqual(updated.effectiveDate);
    expect(mock.deletes).toHaveLength(0);
  });

  it("updates a line in place so its id and createdAt survive the edit", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution], // InventoryExecution
      [baseGoodsReceiptExecutionLine], // InventoryExecutionLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          updateLines: [{ lineId: baseGoodsReceiptExecutionLine.id, linePatch: { quantity: "9" } }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectOk(result as never);
    expect(mock.deletes).toHaveLength(0);
    expect(mock.inserts).toHaveLength(0);
    expect(mock.updates[0].updateValues()).toEqual(expect.objectContaining({ quantity: "9" }));
  });

  it("adds a goods receipt line via addLines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution], // InventoryExecution
      [baseGoodsReceiptExecutionLine], // InventoryExecutionLine (current lines)
      [baseStorageLocation], // StorageLocation bulk fetch
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          addLines: [{ ...receiptLine, unitCost: "12" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectOk(result as never);
    expect(mock.inserts[0].insertRows()).toHaveLength(1);
  });

  it("removes a goods receipt line via removeLineIds", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const secondLine = { ...baseGoodsReceiptExecutionLine, id: "execution-line-2" };
    mock.enqueueResults(
      [baseGoodsReceiptExecution], // InventoryExecution
      [baseGoodsReceiptExecutionLine, secondLine], // InventoryExecutionLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: baseGoodsReceiptExecution.id, removeLineIds: [baseGoodsReceiptExecutionLine.id] },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectOk(result as never);
    expect(mock.deletes).toHaveLength(1);
  });

  it("returns error when goods receipt is not draft", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([postedExecution]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: postedExecution.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

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

  it("returns error when an update targets a missing line", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution], // InventoryExecution
      [baseGoodsReceiptExecutionLine], // InventoryExecutionLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          updateLines: [{ lineId: "missing-line", linePatch: { quantity: "9" } }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

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

  it("returns error when a removal would leave the goods receipt without lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution], // InventoryExecution
      [baseGoodsReceiptExecutionLine], // InventoryExecutionLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: baseGoodsReceiptExecution.id, removeLineIds: [baseGoodsReceiptExecutionLine.id] },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

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

  it("returns error when an added line unit cost is negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution],
      [baseGoodsReceiptExecutionLine],
      [baseStorageLocation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          addLines: [{ ...receiptLine, unitCost: "-1" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidUnitCostError);
    expect(mock.deletes).toHaveLength(0);
  });

  it("returns error when an added line primary quantity is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution],
      [baseGoodsReceiptExecutionLine],
      [baseStorageLocation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          addLines: [{ ...receiptLine, primaryQuantity: "0" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidQuantityError);
    expect(mock.deletes).toHaveLength(0);
  });

  it("returns error when an added line unit conversion rate is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution],
      [baseGoodsReceiptExecutionLine],
      [baseStorageLocation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          addLines: [{ ...receiptLine, unitConversionRate: "0" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, InvalidUnitConversionRateError);
    expect(mock.deletes).toHaveLength(0);
  });

  it("returns error when an added line primary unit differs from item primary unit", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsReceiptExecution],
      [baseGoodsReceiptExecutionLine],
      [baseStorageLocation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsReceiptExecution.id,
          addLines: [{ ...receiptLine, primaryUnitId: "unit-kg" }],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

    expectErr(result as never, PrimaryUnitMismatchError);
    expect(mock.deletes).toHaveLength(0);
  });
});
