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 { ItemNotFoundError, DuplicateLotNumberError } from "../lib/errors.generated";
import { mockItemManagementQueries } from "../testing/commandTestUtils";
import { baseActiveItem, baseActiveLot } from "../testing/fixtures";
import { run } from "./createLot";

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

  const mockGetItemFound = mockItemManagementQueries(baseActiveItem);

  const mockGetItemNotFound = mockItemManagementQueries(null);

  it("returns error when item not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, { lotNumber: "LOT-001", itemId: "nonexistent" }, ctx, mockGetItemNotFound),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
  });

  it("returns error when lot number already exists for item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot]); // duplicate lot found

    const result = await mock.withTx((trx) =>
      run(trx, { lotNumber: "LOT-001", itemId: "item-1" }, ctx, mockGetItemFound),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateLotNumberError);
    }
  });

  it("creates lot with all attributes", async () => {
    const createdLot = {
      ...baseActiveLot,
      id: "new-lot-id",
      lotNumber: "LOT-NEW",
      manufactureDate: new Date("2024-03-01"),
      expirationDate: new Date("2025-03-01"),
      supplierLotReference: "SUP-123",
    };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [createdLot]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          lotNumber: "LOT-NEW",
          itemId: "item-1",
          manufactureDate: new Date("2024-03-01"),
          expirationDate: new Date("2025-03-01"),
          supplierLotReference: "SUP-123",
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.lot.lotNumber).toBe("LOT-NEW");
      expect(result.value.lot.supplierLotReference).toBe("SUP-123");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("creates lot with minimal attributes", async () => {
    const createdLot = {
      ...baseActiveLot,
      id: "new-lot-id",
      lotNumber: "LOT-MIN",
      manufactureDate: null,
      expirationDate: null,
      supplierLotReference: null,
    };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([], [createdLot]);

    const result = await mock.withTx((trx) =>
      run(trx, { lotNumber: "LOT-MIN", itemId: "item-1" }, ctx, mockGetItemFound),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.lot.lotNumber).toBe("LOT-MIN");
      expect(result.value.lot.manufactureDate).toBeNull();
      expect(result.value.lot.expirationDate).toBeNull();
      expect(result.value.lot.supplierLotReference).toBeNull();
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });
});
