/**
 * filekorolheader: 登录日志API - 登录日志相关接口调用
 * 功能：获取登录日志列表、统计、导出等功能
 * 路径：/central-config/monitor/login-log/components/loginLogApi
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SDK生成的API接口
 */
import {
  listLoginLogsApiV1LogsLoginLoginLogsGet,
  getLoginStatisticsApiV1LogsLoginLoginLogsStatisticsGet,
  exportLoginLogsApiV1LogsLoginLoginLogsExportGet
} from '@/lib/api/sdk.gen';

// 登录日志接口
export interface LoginLog {
  id: string;
  created_at: string;
  updated_at: string;
  username: string;
  user_id: string | null;
  status: 'success' | 'failed';
  method: string;
  ip_address: string;
  user_agent: string;
  location: string | null;
  failure_reason: string | null;
  attempt_count: number;
  is_suspicious: boolean;
}

// 分页参数接口
export interface LoginLogsQueryParams {
  page?: number;
  size?: number;
  username?: string;
  status?: string;
  start_time?: string;
  end_time?: string;
  ip_address?: string;
  sort_order?: 'asc' | 'desc';
  order_by?: string;
}

// 分页状态接口
export interface PaginationState {
  page: number;
  size: number;
  total: number;
  totalPages?: number;
  hasNext?: boolean;
  hasPrev?: boolean;
}

// 统计数据接口
export interface LoginStatistics {
  total_logins: number;
  successful_logins: number;
  failed_logins: number;
  unique_users: number;
  success_rate: number;
  suspicious_logins: number;
}

/**
 * 获取登录日志列表
 */
export const fetchLoginLogs = async (params: LoginLogsQueryParams = {}) => {
  try {
    // Get token from localStorage
    const storedUser = localStorage.getItem('user');
    let headers = {};

    if (storedUser) {
      const userData = JSON.parse(storedUser);
      if (userData.token) {
        headers = {
          'Authorization': `Bearer ${userData.token}`
        };
      }
    }

    const response = await listLoginLogsApiV1LogsLoginLoginLogsGet({
      headers,
      query: {
        page: params.page || 1,
        size: params.size || 10,
        username: params.username,
        status: params.status,
        start_time: params.start_time,
        end_time: params.end_time,
        ip_address: params.ip_address,
        sort_order: params.sort_order || 'desc',
        order_by: params.order_by || 'created_at',
      }
    });

    return {
      data: response.data?.data || [],
      page: response.data?.page || 1,
      size: response.data?.size || 10,
      total: response.data?.total || 0,
      totalPages: response.data?.total_pages || 0,
      hasNext: response.data?.has_next || false,
      hasPrev: response.data?.has_prev || false,
    };
  } catch (error) {
    console.error('Failed to fetch login logs:', error);
    throw error;
  }
};

/**
 * 获取登录统计信息
 */
export const fetchLoginStatistics = async () => {
  try {
    // Get token from localStorage
    const storedUser = localStorage.getItem('user');
    let headers = {};

    if (storedUser) {
      const userData = JSON.parse(storedUser);
      if (userData.token) {
        headers = {
          'Authorization': `Bearer ${userData.token}`
        };
      }
    }

    const response = await getLoginStatisticsApiV1LogsLoginLoginLogsStatisticsGet({
      headers
    });
    return response.data;
  } catch (error) {
    console.error('Failed to fetch login statistics:', error);
    throw error;
  }
};

/**
 * 导出登录日志
 */
export const exportLoginLogs = async (params: LoginLogsQueryParams = {}) => {
  try {
    // Get token from localStorage
    const storedUser = localStorage.getItem('user');
    let headers = {};

    if (storedUser) {
      const userData = JSON.parse(storedUser);
      if (userData.token) {
        headers = {
          'Authorization': `Bearer ${userData.token}`
        };
      }
    }

    const response = await exportLoginLogsApiV1LogsLoginLoginLogsExportGet({
      headers,
      query: {
        start_time: params.start_time,
        end_time: params.end_time,
        user_id: params.username, // Map username to user_id for export
      }
    });
    return response.data;
  } catch (error) {
    console.error('Failed to export login logs:', error);
    throw error;
  }
};

/**
 * 转换登录日志数据 - 适配组件使用
 */
export const transformLoginLogData = (log: any): LoginLog => ({
  id: log.id,
  created_at: log.created_at,
  updated_at: log.updated_at,
  username: log.username,
  user_id: log.user_id,
  status: log.status,
  method: log.method,
  ip_address: log.ip_address,
  user_agent: log.user_agent,
  location: log.location,
  failure_reason: log.failure_reason,
  attempt_count: log.attempt_count,
  is_suspicious: log.is_suspicious,
});

/**
 * 批量转换登录日志数据
 */
export const transformLoginLogsList = (logs: any[]): LoginLog[] => {
  return logs.map(transformLoginLogData);
};