import { HttpError } from "../../shared/api/errors";
import {
  httpClient,
  type RequestOptions,
} from "../../shared/api/httpClient";
import type { JsonResult, PageResult } from "../../shared/api/types";
import type { UserSummary } from "../auth/authTypes";
import {
  isUserPage,
  type UserQuery,
} from "./directoryTypes";

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

export function createUserApi(client: UserHttpClient = httpClient) {
  return {
    async getUsers(
      query: UserQuery = {},
      signal?: AbortSignal,
    ): Promise<PageResult<UserSummary>> {
      const result = await client.get<unknown>("users", {
        query: {
          organizationId: query.organizationId,
          includeDescendants: query.includeDescendants,
          keyword: query.keyword,
          status: query.status,
          page: query.page,
          pageSize: query.pageSize,
        },
        signal,
      });
      if (!isUserPage(result.data)) {
        throw new HttpError({
          httpStatus: result.httpStatus,
          code: "INTERNAL_ERROR",
          message: "人员列表响应不符合DMS接口契约",
          details: null,
          requestId: result.requestId,
        });
      }
      return result.data;
    },
  };
}

export const userApi = createUserApi();
export type UserApi = ReturnType<typeof createUserApi>;
