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

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

  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 active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseZone); // already ACTIVE

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

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

  it("returns error when warehouse is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseInactiveLocation) // location found, INACTIVE
      .mockReturnValueOnce(baseInactiveWarehouse); // warehouse is INACTIVE

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

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

  it("reactivates inactive location", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reactivatedLocation = { ...baseInactiveLocation, status: "ACTIVE" };
    spies.select
      .mockReturnValueOnce(baseInactiveLocation) // location found, INACTIVE
      .mockReturnValueOnce(baseActiveWarehouse); // warehouse is ACTIVE
    spies.update.mockReturnValue(reactivatedLocation);

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

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