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, DuplicateLocationNameError } from "../lib/errors.generated";
import { baseStorageLocation } from "../testing/fixtures";
import { run } from "./updateStorageLocation";

describe("updateStorageLocation", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory: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(baseStorageLocation) // location found
      .mockReturnValueOnce({ ...baseStorageLocation, id: "other-location", name: "Existing" }); // duplicate found

    const result = await run(db, { id: baseStorageLocation.id, name: "Existing" }, 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 = { ...baseStorageLocation, name: "Renamed" };
    spies.select
      .mockReturnValueOnce(baseStorageLocation) // location found
      .mockReturnValueOnce(undefined); // no duplicate
    spies.update.mockReturnValue(updatedLocation);

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

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

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

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

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