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

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

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

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

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

  it("returns error when new name conflicts", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseZone) // location found
      .mockReturnValueOnce({ ...baseZone, id: "other-location", name: "Existing Zone" }); // duplicate found

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

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

  it("updates location name", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedLocation = { ...baseZone, name: "Renamed Zone" };
    spies.select
      .mockReturnValueOnce(baseZone) // location found
      .mockReturnValueOnce(undefined); // no duplicate
    spies.update.mockReturnValue(updatedLocation);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.storageLocation.name).toBe("Renamed Zone");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("updates storage condition", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedLocation = { ...baseZone, storageCondition: "cold" };
    spies.select.mockReturnValueOnce(baseZone); // location found
    spies.update.mockReturnValue(updatedLocation);

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

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