import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { WarehouseNotFoundError, WarehouseNotActiveError } from "../lib/errors.generated";
import { baseActiveWarehouse, baseInactiveWarehouse } from "../testing/fixtures";
import { run } from "./deactivateWarehouse";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("returns error when warehouse not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "nonexistent" }, ctx);

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

  it("returns error when warehouse already inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactiveWarehouse);

    const result = await run(db, { id: baseInactiveWarehouse.id }, ctx);

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

  it("deactivates active warehouse", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedWarehouse = { ...baseActiveWarehouse, status: "INACTIVE" };
    spies.select.mockReturnValueOnce(baseActiveWarehouse);
    spies.update.mockReturnValue(deactivatedWarehouse);

    const result = await run(db, { id: baseActiveWarehouse.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.warehouse.status).toBe("INACTIVE");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("historical records preserved after deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedWarehouse = {
      ...baseActiveWarehouse,
      status: "INACTIVE",
      name: "Main Warehouse",
      siteId: "site-1",
    };
    spies.select.mockReturnValueOnce(baseActiveWarehouse);
    spies.update.mockReturnValue(deactivatedWarehouse);

    const result = await run(db, { id: baseActiveWarehouse.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      // All fields besides status remain intact
      expect(result.value.warehouse.name).toBe("Main Warehouse");
      expect(result.value.warehouse.siteId).toBe("site-1");
      expect(result.value.warehouse.id).toBe(baseActiveWarehouse.id);
    }
  });
});
