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,
  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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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

  it("returns error when already inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactiveLocation]);

    const result = await mock.withTx((trx) => run(trx, { id: baseInactiveLocation.id }, ctx));

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

  it("deactivates location", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedLocation = { ...baseStorageLocation, status: "INACTIVE" };
    mock.enqueueResults([baseStorageLocation], [deactivatedLocation]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.storageLocation.status).toBe("INACTIVE");
    }
    expect(mock.updates).toHaveLength(1);
  });
});
