import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStorageLocation],
      [{ ...baseStorageLocation, id: "other-location", name: "Existing" }],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const updatedLocation = { ...baseStorageLocation, name: "Renamed" };
    mock.enqueueResults([baseStorageLocation], [], [updatedLocation]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseStorageLocation.id, name: "Renamed" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.storageLocation.name).toBe("Renamed");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("updates storage condition", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedLocation = { ...baseStorageLocation, storageCondition: "cold" };
    mock.enqueueResults([baseStorageLocation], [updatedLocation]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseStorageLocation.id, storageCondition: "cold" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.storageLocation.storageCondition).toBe("cold");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
