import { HttpError } from "../../shared/api/errors";
import {
  httpClient,
  type RequestOptions,
} from "../../shared/api/httpClient";
import type { JsonResult } from "../../shared/api/types";
import {
  isOrganizationTree,
  type OrganizationNode,
  type OrganizationTreeQuery,
} from "./directoryTypes";

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

export function createOrganizationApi(
  client: OrganizationHttpClient = httpClient,
) {
  return {
    async getTree(
      query: OrganizationTreeQuery = {},
      signal?: AbortSignal,
    ): Promise<OrganizationNode[]> {
      const result = await client.get<unknown>("organizations/tree", {
        query: {
          keyword: query.keyword,
          status: query.status,
        },
        signal,
      });
      if (!isOrganizationTree(result.data)) {
        throw new HttpError({
          httpStatus: result.httpStatus,
          code: "INTERNAL_ERROR",
          message: "组织树响应不符合DMS接口契约",
          details: null,
          requestId: result.requestId,
        });
      }
      return result.data;
    },
  };
}

export const organizationApi = createOrganizationApi();
export type OrganizationApi = ReturnType<typeof createOrganizationApi>;
