import { HttpError } from "../../shared/api/errors";
import { httpClient, type RequestOptions } from "../../shared/api/httpClient";
import type { JsonResult, PageResult } from "../../shared/api/types";
import {
  isAuditActionStatisticsData,
  isAuditLogPage,
  isAuditTrendData,
  isAuditUserStatisticsData,
  type AuditActionStatisticsItem,
  type AuditLogQuery,
  type AuditLogSummary,
  type AuditTimeRange,
  type AuditTrendItem,
  type AuditTrendQuery,
  type AuditUserStatisticsItem,
  type AuditUserStatisticsQuery,
} from "./auditTypes";

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

function contractError(result: JsonResult<unknown>, target: string): HttpError {
  return new HttpError({
    httpStatus: result.httpStatus,
    code: "INTERNAL_ERROR",
    message: `${target}响应不符合DMS接口契约`,
    details: null,
    requestId: result.requestId,
  });
}

export function createAuditApi(client: AuditHttpClient = httpClient) {
  return {
    async logs(
      query: AuditLogQuery,
      signal?: AbortSignal,
    ): Promise<PageResult<AuditLogSummary>> {
      const result = await client.get<unknown>("audit/logs", {
        query: { ...query },
        signal,
      });
      if (!isAuditLogPage(result.data)) {
        throw contractError(result, "审计日志");
      }
      return result.data;
    },

    async trend(
      query: AuditTrendQuery,
      signal?: AbortSignal,
    ): Promise<AuditTrendItem[]> {
      const result = await client.get<unknown>("audit/statistics/trend", {
        query: { ...query },
        signal,
      });
      if (!isAuditTrendData(result.data)) {
        throw contractError(result, "审计趋势");
      }
      return result.data.items;
    },

    async actions(
      query: AuditTimeRange,
      signal?: AbortSignal,
    ): Promise<AuditActionStatisticsItem[]> {
      const result = await client.get<unknown>("audit/statistics/actions", {
        query: { ...query },
        signal,
      });
      if (!isAuditActionStatisticsData(result.data)) {
        throw contractError(result, "动作分布");
      }
      return result.data.items;
    },

    async users(
      query: AuditUserStatisticsQuery,
      signal?: AbortSignal,
    ): Promise<AuditUserStatisticsItem[]> {
      const result = await client.get<unknown>("audit/statistics/users", {
        query: { ...query },
        signal,
      });
      if (!isAuditUserStatisticsData(result.data)) {
        throw contractError(result, "活跃用户");
      }
      return result.data.items;
    },
  };
}

export const auditApi = createAuditApi();
export type AuditApi = ReturnType<typeof createAuditApi>;
