import request from "@/utils/request";
import type { PaginationParams, PaginationResponse } from "@/types/api";

export interface Log {
  id: number;
  userId?: number;
  action: string;
  content?: string;
  ip?: string;
  userAgent?: string;
  createTime?: string;
  user?: {
    id: number;
    username: string;
    nickname: string;
  };
}

export interface LogQueryParams extends PaginationParams {
  userId?: number;
  action?: string;
  keyword?: string;
  ip?: string;
  startTime?: string;
  endTime?: string;
}

export interface LogStatistics {
  totalCount: number;
  recentCount: number;
  days: number;
  actionStats: Array<{
    action: string;
    count: number;
  }>;
  dailyStats: Array<{
    date: string;
    count: number;
  }>;
}

export interface CleanLogsResult {
  deleted: number;
  cutoffDate: string;
}

// 获取日志列表
export async function getLogsList(
  params: LogQueryParams
): Promise<PaginationResponse<Log>> {
  const response = await request.get<any, PaginationResponse<Log>>("/logs", {
    params,
  });
  return response;
}

// 获取单个日志详情
export async function getLogDetail(id: number): Promise<Log> {
  const response = await request.get<any, Log>(`/logs/${id}`);
  return response;
}

// 获取日志统计信息
export async function getLogStatistics(days: number = 7): Promise<LogStatistics> {
  const response = await request.get<any, LogStatistics>("/logs/statistics", {
    params: { days },
  });
  return response;
}

// 批量删除日志
export async function deleteLogs(ids: number[]): Promise<{ count: number }> {
  const response = await request.delete<any, { count: number }>("/logs", {
    data: { ids },
  });
  return response;
}

// 清理过期日志
export async function cleanOldLogs(daysToKeep: number = 90): Promise<CleanLogsResult> {
  const response = await request.post<any, CleanLogsResult>("/logs/clean", {
    daysToKeep,
  });
  return response;
}

// 兼容性导出：保留 logsApi 对象
export const logsApi = {
  getList: getLogsList,
  getDetail: getLogDetail,
  getStatistics: getLogStatistics,
  delete: deleteLogs,
  clean: cleanOldLogs,
};

