import type { CommandContext } from "@tailor-platform/erp-kit/core";
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 { baseStorageLocation, baseInactiveLocation } from "../testing/fixtures";
import { run } from "./deactivateStorageLocation";

describe("deactivateStorageLocation", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory: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 = { ...baseStorageLocation, status: "INACTIVE" };
    spies.select.mockReturnValueOnce(baseStorageLocation);
    spies.update.mockReturnValue(deactivatedLocation);

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

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