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,
  StorageLocationNotFoundError,
  DuplicateSerialNumberError,
} from "../lib/errors.generated";
import { mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseActiveItem2,
  baseAvailableSerial,
  baseStorageLocation,
} from "../testing/fixtures";
import { run } from "./assignSerialNumber";

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

  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,
        { serialNumber: "SN-001", itemId: "nonexistent", storageLocationId: "location-1" },
        ctx,
        mockGetItemNotFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
  });

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

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

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

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

  it("assigns serial in AVAILABLE state", async () => {
    const createdSerial = {
      ...baseAvailableSerial,
      id: "new-serial-id",
      serialNumber: "SN-NEW",
    };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStorageLocation], // location found
      [], // no duplicate
      [createdSerial],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { serialNumber: "SN-NEW", itemId: "item-1", storageLocationId: "location-1" },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.serialNumber.serialNumber).toBe("SN-NEW");
      expect(result.value.serialNumber.status).toBe("AVAILABLE");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("allows same serial number for different items", async () => {
    const createdSerial = {
      ...baseAvailableSerial,
      id: "new-serial-id",
      serialNumber: "SN-001",
      itemId: "item-2",
    };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStorageLocation], // location found
      [], // no duplicate for item-2
      [createdSerial],
    );

    const mockGetItem2 = mockItemManagementQueries(baseActiveItem2);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { serialNumber: "SN-001", itemId: "item-2", storageLocationId: "location-1" },
        ctx,
        mockGetItem2,
      ),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.serialNumber.serialNumber).toBe("SN-001");
      expect(result.value.serialNumber.itemId).toBe("item-2");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });
});
