import { HttpError } from "../../shared/api/errors";
import {
  httpClient,
  type RequestOptions,
} from "../../shared/api/httpClient";
import type { JsonResult } from "../../shared/api/types";
import {
  isUiDictionaries,
  type UiDictionaries,
} from "./dictionaryTypes";

interface DictionaryHttpClient {
  get<T>(path: string, options?: RequestOptions): Promise<JsonResult<T>>;
}

export function createDictionaryApi(
  client: DictionaryHttpClient = httpClient,
) {
  return {
    async getUiDictionaries(signal?: AbortSignal): Promise<UiDictionaries> {
      const result = await client.get<unknown>("config/ui-dictionaries", {
        signal,
      });
      if (!isUiDictionaries(result.data)) {
        throw new HttpError({
          httpStatus: result.httpStatus,
          code: "INTERNAL_ERROR",
          message: "系统字典响应不符合DMS接口契约",
          details: null,
          requestId: result.requestId,
        });
      }
      return result.data;
    },
  };
}

export const dictionaryApi = createDictionaryApi();
export type DictionaryApi = ReturnType<typeof createDictionaryApi>;
