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 async function getLogsList(
  params: LogQueryParams
): Promise<PaginationResponse<Log>> {
  const response = await request.get<any, PaginationResponse<Log>>("/api/sys-log/page", {
    params,
  });
  return response;
}

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

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

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

// 清理过期日志
export async function cleanOldLogs(daysToKeep?: number): Promise<number> {
  const response = await request.post<any, number>("/api/sys-log/clean", null, {
    params: daysToKeep ? { days: daysToKeep } : {},
  });
  return response;
}

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

