import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  StorageLocationNotFoundError,
  StorageLocationNotActiveError,
} from "../lib/errors.generated";
import { baseZone, baseInactiveLocation } from "../testing/fixtures";
import { run } from "./deactivateStorageLocation";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("returns error when 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(StorageLocationNotFoundError);
    }
  });

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

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

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

  it("deactivates location", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedLocation = { ...baseZone, status: "INACTIVE" };
    spies.select.mockReturnValueOnce(baseZone);
    spies.update.mockReturnValue(deactivatedLocation);

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

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

  it("does not cascade to child bins", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedZone = { ...baseZone, status: "INACTIVE" };
    spies.select.mockReturnValueOnce(baseZone);
    spies.update.mockReturnValue(deactivatedZone);

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

    expect(result.ok).toBe(true);
    // Only one update call for the zone itself, no cascading updates for child bins
    expect(spies.update).toHaveBeenCalledTimes(1);
  });
});
