import { apiClient } from '@/services/api/client';

// BE-PAGE-001: Dashboard service for fetching dashboard data

export interface DashboardStats {
  tracks_played: number;
  messages_sent: number;
  favorites: number;
  active_friends: number;
  tracks_played_change?: string;
  messages_sent_change?: string;
  favorites_change?: string;
  active_friends_change?: string;
}

export interface RecentActivity {
  id: string;
  type: 'track_upload' | 'message_received' | 'favorite_added' | 'playlist_created' | 'comment_added';
  title: string;
  description?: string;
  timestamp: string;
  icon?: string;
}

export interface DashboardData {
  stats: DashboardStats;
  recent_activity: RecentActivity[];
}

/**
 * Fetch dashboard statistics
 */
export async function getDashboardStats(): Promise<DashboardStats> {
  try {
    // Try to get stats from audit endpoint
    const auditResponse = await apiClient.get('/api/v1/audit/stats');
    
    // Calculate stats from audit data
    const stats: DashboardStats = {
      tracks_played: 0,
      messages_sent: 0,
      favorites: 0,
      active_friends: 0,
    };

    if (auditResponse.data?.stats) {
      const auditStats = auditResponse.data.stats;
      
      // Count different action types
      auditStats.forEach((stat: any) => {
        if (stat.action === 'upload' || stat.action === 'play') {
          stats.tracks_played += stat.action_count || 0;
        }
        if (stat.action === 'message_sent' || stat.action?.includes('message')) {
          stats.messages_sent += stat.action_count || 0;
        }
        if (stat.action === 'favorite' || stat.action?.includes('favorite')) {
          stats.favorites += stat.action_count || 0;
        }
      });
    }

    return stats;
  } catch (error) {
    console.error('Failed to fetch dashboard stats:', error);
    // Return default stats on error
    return {
      tracks_played: 0,
      messages_sent: 0,
      favorites: 0,
      active_friends: 0,
    };
  }
}

/**
 * Fetch recent user activity
 */
export async function getRecentActivity(limit: number = 10): Promise<RecentActivity[]> {
  try {
    const response = await apiClient.get('/api/v1/audit/activity', {
      params: { limit },
    });

    if (response.data?.activity) {
      return response.data.activity.map((item: any) => ({
        id: item.id || '',
        type: mapActionToType(item.action),
        title: formatActivityTitle(item.action, item.resource, item.metadata),
        description: formatActivityDescription(item.action, item.metadata),
        timestamp: item.timestamp || item.created_at || new Date().toISOString(),
      }));
    }

    return [];
  } catch (error) {
    console.error('Failed to fetch recent activity:', error);
    return [];
  }
}

/**
 * Map audit action to activity type
 */
function mapActionToType(action: string): RecentActivity['type'] {
  if (action.includes('upload') || action.includes('track')) {
    return 'track_upload';
  }
  if (action.includes('message') || action.includes('chat')) {
    return 'message_received';
  }
  if (action.includes('favorite') || action.includes('like')) {
    return 'favorite_added';
  }
  if (action.includes('playlist')) {
    return 'playlist_created';
  }
  if (action.includes('comment')) {
    return 'comment_added';
  }
  return 'track_upload';
}

/**
 * Format activity title from audit log
 */
function formatActivityTitle(
  action: string,
  _resource: string,
  metadata: any
): string {
  if (action.includes('upload')) {
    return 'Nouvelle piste ajoutée';
  }
  if (action.includes('message')) {
    const username = metadata?.username || metadata?.from_user || 'un utilisateur';
    return `Message reçu de @${username}`;
  }
  if (action.includes('favorite') || action.includes('like')) {
    return 'Nouveau favori ajouté';
  }
  if (action.includes('playlist')) {
    return 'Nouvelle playlist créée';
  }
  if (action.includes('comment')) {
    return 'Nouveau commentaire';
  }
  return 'Nouvelle activité';
}

/**
 * Format activity description from audit log
 */
function formatActivityDescription(_action: string, metadata: any): string {
  if (metadata?.file_name) {
    return metadata.file_name;
  }
  if (metadata?.track_title) {
    return metadata.track_title;
  }
  if (metadata?.playlist_name) {
    return metadata.playlist_name;
  }
  return '';
}

/**
 * Fetch complete dashboard data
 */
export async function getDashboardData(): Promise<DashboardData> {
  const [stats, recentActivity] = await Promise.all([
    getDashboardStats(),
    getRecentActivity(10),
  ]);

  return {
    stats,
    recent_activity: recentActivity,
  };
}

