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

// 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;
  period?: string; // Time period for statistics: "7d", "30d", "90d", "all"
}

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

export interface TrackPreview {
  id: string;
  title: string;
  artist: string;
  duration: number;
  cover_art_path?: string;
  play_count: number;
  like_count: number;
  created_at: string;
}

export interface LibraryPreview {
  items: TrackPreview[];
  total_count: number;
  has_more: boolean;
}

export interface DashboardData {
  stats: DashboardStats;
  recent_activity: RecentActivity[];
  library_preview?: LibraryPreview; // Optional for backward compatibility
}

// Action 2.1.1.6: Removed old separate API calls (getDashboardStats, getRecentActivity)
// All dashboard data now comes from the aggregated /api/v1/dashboard endpoint

/**
 * Fetch complete dashboard data from aggregated endpoint
 * Action 2.1.1.3: Use new /api/v1/dashboard endpoint instead of multiple calls
 */
export async function getDashboardData(
  options?: {
    activityLimit?: number;
    libraryLimit?: number;
    statsPeriod?: '7d' | '30d' | '90d' | 'all';
  },
): Promise<DashboardData> {
  try {
    const params: Record<string, string | number> = {};
    if (options?.activityLimit) {
      params.activity_limit = options.activityLimit;
    }
    if (options?.libraryLimit) {
      params.library_limit = options.libraryLimit;
    }
    if (options?.statsPeriod) {
      params.stats_period = options.statsPeriod;
    }

    const response = await apiClient.get('/dashboard', { params });

    // Response is already unwrapped by API client interceptor
    // Expected format: { success: true, data: DashboardResponse }
    const dashboardData = response.data;

    if (!dashboardData) {
      throw new Error('Invalid dashboard response format');
    }

    return {
      stats: dashboardData.stats || {
        tracks_played: 0,
        messages_sent: 0,
        favorites: 0,
        active_friends: 0,
        period: options?.statsPeriod || '30d',
      },
      recent_activity: dashboardData.recent_activity || [],
      library_preview: dashboardData.library_preview,
    };
  } catch (error) {
    logger.error('Failed to fetch dashboard data from aggregated endpoint', {
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
      options,
    });

    // Action 2.1.1.6: Return default/empty data on error instead of fallback to old methods
    // Old separate API calls have been removed
    return {
      stats: {
        tracks_played: 0,
        messages_sent: 0,
        favorites: 0,
        active_friends: 0,
        period: options?.statsPeriod || '30d',
      },
      recent_activity: [],
      library_preview: undefined,
    };
  }
}
