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 {
  EmptyIssueLinesError,
  InvalidQuantityError,
  InvalidUnitConversionRateError,
  IssueLineNotFoundError,
  PrimaryUnitMismatchError,
} from "../lib/errors.generated";
import { expectErr, expectOk, mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseGoodsIssueExecution,
  baseGoodsIssueExecutionLine,
  baseStorageLocation,
} from "../testing/fixtures";
import { run } from "./updateGoodsIssue";

describe("updateGoodsIssue", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory:inventoryOperation:updateGoodsIssue"],
  };
  const issueLine = {
    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 issue", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = {
      ...baseGoodsIssueExecution,
      effectiveDate: new Date("2024-02-01T00:00:00.000Z"),
    };
    mock.enqueueResults(
      [baseGoodsIssueExecution], // InventoryExecution
      [baseGoodsIssueExecutionLine], // InventoryExecutionLine (current lines)
      [updated], // updateTable InventoryExecution
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: baseGoodsIssueExecution.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(
      [baseGoodsIssueExecution], // InventoryExecution
      [baseGoodsIssueExecutionLine], // InventoryExecutionLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsIssueExecution.id,
          updateLines: [{ lineId: baseGoodsIssueExecutionLine.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 issue line via addLines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseGoodsIssueExecution], // InventoryExecution
      [baseGoodsIssueExecutionLine], // InventoryExecutionLine (current lines)
      [baseStorageLocation], // StorageLocation bulk fetch
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsIssueExecution.id,
          addLines: [issueLine],
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
      ),
    );

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

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

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

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

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

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

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

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

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

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

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsIssueExecution.id,
          addLines: [{ ...issueLine, 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(
      [baseGoodsIssueExecution],
      [baseGoodsIssueExecutionLine],
      [baseStorageLocation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: baseGoodsIssueExecution.id,
          addLines: [{ ...issueLine, 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(
      [baseGoodsIssueExecution],
      [baseGoodsIssueExecutionLine],
      [baseStorageLocation],
    );

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

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