/**
 * Audit API - Feature API Layer
 * Action 6.1.1.10: Update feature API files to use services
 * 
 * This file provides the implementation layer for audit API operations.
 * Currently, there is no unified service layer for admin/audit operations.
 * 
 * TODO: Consider creating @/services/api/admin (adminApi) or @/services/api/audit (auditApi)
 * in the future to align with the service layer pattern used for tracks, auth, users, and playlists.
 */

import { apiClient } from '@/services/api/client';
import { AuditLog, AuditStats, SuspiciousActivity } from '@/types/api';
import { AxiosError } from 'axios';

/**
 * Audit API Service
 * Implémente les endpoints audit pour les admins selon le backend
 * Endpoints:
 * - GET /audit/logs (protected) - Rechercher des logs d'audit
 * - GET /audit/stats (protected) - Statistiques d'audit
 * - GET /audit/activity (protected) - Activité d'un utilisateur
 * - GET /audit/suspicious (protected) - Détecter les activités suspectes
 * - GET /audit/ip/:ip (protected) - Activité d'une IP
 * - GET /audit/logs/:id (protected) - Récupérer un log spécifique
 * - POST /audit/cleanup (protected) - Nettoyer les anciens logs
 */

export interface SearchAuditLogsParams {
  action?: string;
  resource?: string;
  start_date?: string; // Format: YYYY-MM-DD
  end_date?: string; // Format: YYYY-MM-DD
  limit?: number; // Default: 50, max: 100
  offset?: number; // Default: 0
}

export interface SearchAuditLogsResponse {
  logs: AuditLog[];
  count: number;
  query: SearchAuditLogsParams;
}

export interface GetAuditStatsParams {
  start_date?: string; // Format: YYYY-MM-DD
  end_date?: string; // Format: YYYY-MM-DD
}

export interface GetAuditStatsResponse {
  user_id: string;
  start_date: string;
  end_date: string;
  stats: AuditStats[];
}

export interface GetUserActivityParams {
  limit?: number; // Default: 50, max: 100
}

export interface GetUserActivityResponse {
  user_id: string;
  activity: AuditLog[];
  count: number;
}

export interface DetectSuspiciousActivityParams {
  hours?: number; // Default: 24, max: 168 (7 days)
}

export interface DetectSuspiciousActivityResponse {
  user_id: string;
  hours: number;
  activities: SuspiciousActivity[];
  count: number;
}

export interface GetIPActivityParams {
  limit?: number; // Default: 50, max: 100
}

export interface GetIPActivityResponse {
  user_id: string;
  ip_address: string;
  activity: AuditLog[];
  count: number;
}

export interface CleanupOldLogsParams {
  retention_days?: number; // Default: 90, max: 365
}

export interface CleanupOldLogsResponse {
  message: string;
  deleted_count: number;
  retention_days: number;
}

export interface GetAuditLogResponse {
  log: AuditLog;
}

/**
 * Recherche des logs d'audit
 * @param params Paramètres de recherche (action, resource, dates, pagination)
 * @returns Liste des logs d'audit correspondants
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function searchAuditLogs(
  params?: SearchAuditLogsParams,
): Promise<SearchAuditLogsResponse> {
  try {
    const response = await apiClient.get<SearchAuditLogsResponse>(
      '/audit/logs',
      { params },
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to access audit logs',
      );
    }
    throw error;
  }
}

/**
 * Récupère les statistiques d'audit
 * @param params Paramètres de date (start_date, end_date)
 * @returns Statistiques d'audit par action et ressource
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function getAuditStats(
  params?: GetAuditStatsParams,
): Promise<GetAuditStatsResponse> {
  try {
    const response = await apiClient.get<GetAuditStatsResponse>(
      '/audit/stats',
      {
        params,
      },
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to access audit stats',
      );
    }
    throw error;
  }
}

/**
 * Récupère l'activité d'un utilisateur
 * @param params Paramètres (limit)
 * @returns Liste des logs d'audit de l'utilisateur authentifié
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function getUserActivity(
  params?: GetUserActivityParams,
): Promise<GetUserActivityResponse> {
  try {
    const response = await apiClient.get<GetUserActivityResponse>(
      '/audit/activity',
      { params },
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to access user activity',
      );
    }
    throw error;
  }
}

/**
 * Détecte les activités suspectes
 * @param params Paramètres (hours)
 * @returns Liste des activités suspectes détectées
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function detectSuspiciousActivity(
  params?: DetectSuspiciousActivityParams,
): Promise<DetectSuspiciousActivityResponse> {
  try {
    const response = await apiClient.get<DetectSuspiciousActivityResponse>(
      '/audit/suspicious',
      { params },
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to detect suspicious activity',
      );
    }
    throw error;
  }
}

/**
 * Récupère l'activité d'une adresse IP
 * @param ip Adresse IP à rechercher
 * @param params Paramètres (limit)
 * @returns Liste des logs d'audit pour cette IP
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function getIPActivity(
  ip: string,
  params?: GetIPActivityParams,
): Promise<GetIPActivityResponse> {
  try {
    const response = await apiClient.get<GetIPActivityResponse>(
      `/audit/ip/${ip}`,
      { params },
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to access IP activity',
      );
    }
    throw error;
  }
}

/**
 * Récupère un log d'audit spécifique
 * @param id ID du log d'audit
 * @returns Le log d'audit
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function getAuditLog(id: string): Promise<GetAuditLogResponse> {
  try {
    const response = await apiClient.get<GetAuditLogResponse>(
      `/audit/logs/${id}`,
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to access audit logs',
      );
    }
    throw error;
  }
}

/**
 * Nettoie les anciens logs d'audit
 * @param params Paramètres (retention_days)
 * @returns Nombre de logs supprimés
 * @throws Error si l'utilisateur n'a pas les permissions admin (403)
 */
export async function cleanupOldLogs(
  params?: CleanupOldLogsParams,
): Promise<CleanupOldLogsResponse> {
  try {
    const response = await apiClient.post<CleanupOldLogsResponse>(
      '/audit/cleanup',
      undefined,
      { params },
    );
    return response.data;
  } catch (error) {
    if (error instanceof AxiosError && error.response?.status === 403) {
      throw new Error(
        'Forbidden: You do not have admin permissions to cleanup audit logs',
      );
    }
    throw error;
  }
}
