import { HttpError } from "../../shared/api/errors";
import { httpClient, type RequestOptions } from "../../shared/api/httpClient";
import type { JsonResult } from "../../shared/api/types";
import {
  isDocumentStatistics,
  type DocumentStatistics,
} from "./statisticsTypes";

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

export function createStatisticsApi(
  client: StatisticsHttpClient = httpClient,
) {
  return {
    async documents(signal?: AbortSignal): Promise<DocumentStatistics> {
      const result = await client.get<unknown>("statistics/documents", {
        signal,
      });
      if (!isDocumentStatistics(result.data)) {
        throw new HttpError({
          httpStatus: result.httpStatus,
          code: "INTERNAL_ERROR",
          message: "文档统计响应不符合DMS接口契约",
          details: null,
          requestId: result.requestId,
        });
      }
      return result.data;
    },
  };
}

export const statisticsApi = createStatisticsApi();
export type StatisticsApi = ReturnType<typeof createStatisticsApi>;

