import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it, vi } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  StorageLocationNotFoundError,
  StorageLocationNotInactiveError,
  SiteInactiveError,
} from "../lib/errors.generated";
import type { OrganizationQueries } from "../module";
import {
  baseStorageLocation,
  baseInactiveLocation,
  baseActiveSite,
  baseInactiveSite,
} from "../testing/fixtures";
import { run } from "./reactivateStorageLocation";

const ok = <T>(value: T) => ({ ok: true as const, value });

function mockOrgQueries(site: unknown): Pick<OrganizationQueries, "getSite"> {
  return {
    getSite: vi.fn().mockResolvedValue(ok({ site })),
  } as unknown as Pick<OrganizationQueries, "getSite">;
}

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

  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, mockOrgQueries(baseActiveSite)),
    );

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

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

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

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

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

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

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

  it("reactivates inactive location", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivatedLocation = { ...baseInactiveLocation, status: "ACTIVE" };
    mock.enqueueResults([baseInactiveLocation], [reactivatedLocation]);

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

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