import { expect } from "vitest";
import type { ItemManagementQueries, OrganizationQueries } from "../module";

export type ItemManagementQueryItem = Awaited<
  ReturnType<ItemManagementQueries["getItem"]>
>["value"]["item"];

export function mockItemManagementQueries(
  item: ItemManagementQueryItem,
): Pick<ItemManagementQueries, "getItem"> {
  return {
    getItem: () => Promise.resolve({ ok: true, value: { item } }),
  };
}

export type OrganizationQuerySite = Awaited<
  ReturnType<OrganizationQueries["getSite"]>
>["value"]["site"];

export function mockOrganizationQueries(
  site: OrganizationQuerySite,
): Pick<OrganizationQueries, "getSite"> {
  return {
    getSite: () => Promise.resolve({ ok: true, value: { site } }),
  };
}

interface OkResult<T> {
  ok: true;
  value: T;
}

interface ErrResult {
  ok: false;
  error: unknown;
}

export function expectErr(
  result: OkResult<unknown> | ErrResult,
  errorClass: abstract new (...args: never[]) => Error,
) {
  expect(result.ok).toBe(false);
  if (!result.ok) {
    expect(result.error).toBeInstanceOf(errorClass);
  }
}

export function expectOk<T>(result: OkResult<T> | ErrResult) {
  expect(result.ok).toBe(true);
  if (!result.ok) {
    throw result.error;
  }
  return result.value;
}
