import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  SiteNotFoundError,
  SiteInactiveError,
  DuplicateWarehouseNameError,
} from "../lib/errors.generated";
import { baseActiveWarehouse } from "../testing/fixtures";
import { run, type OrganizationQueries } from "./createWarehouse";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const activeSite = { id: "site-1", name: "Main Site", status: "ACTIVE" };
  const inactiveSite = { id: "site-2", name: "Closed Site", status: "INACTIVE" };

  const makeQueries = (
    site: { id: string; status: string; name: string } | null,
  ): Pick<OrganizationQueries, "getSite"> => ({
    getSite: () =>
      Promise.resolve({
        ok: true as const,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
        value: { site: site as any },
      }),
  });

  it("returns error when site not found", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeQueries(null);

    const result = await run(db, { name: "Warehouse A", siteId: "nonexistent" }, ctx, queries);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SiteNotFoundError);
    }
  });

  it("returns error when site is inactive", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeQueries(inactiveSite);

    const result = await run(db, { name: "Warehouse A", siteId: "site-2" }, ctx, queries);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SiteInactiveError);
    }
  });

  it("returns error when warehouse name already exists at site", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeQueries(activeSite);
    spies.select.mockReturnValueOnce(baseActiveWarehouse);

    const result = await run(db, { name: "Main Warehouse", siteId: "site-1" }, ctx, queries);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DuplicateWarehouseNameError);
    }
  });

  it("creates warehouse with ACTIVE status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeQueries(activeSite);
    const createdWarehouse = {
      ...baseActiveWarehouse,
      id: "new-warehouse-id",
      name: "New Warehouse",
    };

    spies.select.mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(createdWarehouse);

    const result = await run(db, { name: "New Warehouse", siteId: "site-1" }, ctx, queries);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.warehouse.status).toBe("ACTIVE");
      expect(result.value.warehouse.name).toBe("New Warehouse");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("creates warehouse with optional storage condition", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeQueries(activeSite);
    const createdWarehouse = {
      ...baseActiveWarehouse,
      id: "new-warehouse-id",
      name: "Cold Warehouse",
      storageCondition: "cold",
    };

    spies.select.mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(createdWarehouse);

    const result = await run(
      db,
      { name: "Cold Warehouse", siteId: "site-1", storageCondition: "cold" },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.warehouse.storageCondition).toBe("cold");
    }
  });

  it("creates warehouse with optional capacity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeQueries(activeSite);
    const createdWarehouse = {
      ...baseActiveWarehouse,
      id: "new-warehouse-id",
      name: "Large Warehouse",
      capacity: 10000,
    };

    spies.select.mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(createdWarehouse);

    const result = await run(
      db,
      { name: "Large Warehouse", siteId: "site-1", capacity: 10000 },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.warehouse.capacity).toBe(10000);
    }
  });
});
