/**
 * Auth Service
 * API client for authentication endpoints
 * @updated ST4.1 - Migrated to centralized apiClient with auto-refresh
 */

import { apiClient, clearTokens } from '../lib/apiClient';

// ============================================================================
// Types
// ============================================================================

export interface ActiveSession {
  id: string;
  userAgent: string;
  ipAddress: string;
  deviceType?: string;
  browser?: string;
  os?: string;
  countryCode?: string;
  city?: string;
  createdAt: string;
  lastActiveAt: string;
  isCurrent: boolean;
}

export interface DeviceInfo {
  type: 'desktop' | 'mobile' | 'tablet' | 'unknown';
  os: string;
  browser: string;
}

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Parse user agent string to extract device info
 */
export function parseUserAgent(userAgent: string): DeviceInfo {
  const ua = userAgent.toLowerCase();

  // Detect device type
  let type: DeviceInfo['type'] = 'unknown';
  if (/mobile|android|iphone|ipod|blackberry|opera mini|iemobile/i.test(ua)) {
    type = 'mobile';
  } else if (/ipad|tablet|playbook|silk/i.test(ua)) {
    type = 'tablet';
  } else if (/windows|macintosh|linux|cros/i.test(ua)) {
    type = 'desktop';
  }

  // Detect OS
  let os = 'Unknown OS';
  if (/windows nt 10/i.test(ua)) os = 'Windows 10/11';
  else if (/windows nt 6.3/i.test(ua)) os = 'Windows 8.1';
  else if (/windows nt 6.2/i.test(ua)) os = 'Windows 8';
  else if (/windows nt 6.1/i.test(ua)) os = 'Windows 7';
  else if (/windows/i.test(ua)) os = 'Windows';
  else if (/macintosh|mac os x/i.test(ua)) os = 'macOS';
  else if (/iphone|ipad|ipod/i.test(ua)) os = 'iOS';
  else if (/android/i.test(ua)) os = 'Android';
  else if (/linux/i.test(ua)) os = 'Linux';
  else if (/cros/i.test(ua)) os = 'Chrome OS';

  // Detect browser
  let browser = 'Unknown Browser';
  if (/edg/i.test(ua)) browser = 'Edge';
  else if (/chrome/i.test(ua) && !/edg/i.test(ua)) browser = 'Chrome';
  else if (/firefox/i.test(ua)) browser = 'Firefox';
  else if (/safari/i.test(ua) && !/chrome/i.test(ua)) browser = 'Safari';
  else if (/opera|opr/i.test(ua)) browser = 'Opera';
  else if (/msie|trident/i.test(ua)) browser = 'Internet Explorer';

  return { type, os, browser };
}

/**
 * Format relative time
 */
export function formatRelativeTime(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);

  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins} min ago`;
  if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
  if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;

  return date.toLocaleDateString();
}

// ============================================================================
// Session Management API
// ============================================================================

/**
 * Get all active sessions for the current user
 */
export async function getSessions(): Promise<ActiveSession[]> {
  try {
    const response = await apiClient.get('/auth/sessions');
    return response.data.data || [];
  } catch (error) {
    console.error('Failed to fetch sessions:', error);
    throw new Error('Failed to fetch active sessions');
  }
}

/**
 * Revoke a specific session
 */
export async function revokeSession(sessionId: string): Promise<void> {
  try {
    await apiClient.delete(`/auth/sessions/${sessionId}`);
  } catch (error) {
    console.error('Failed to revoke session:', error);
    throw new Error('Failed to revoke session');
  }
}

/**
 * Revoke all sessions except the current one
 */
export async function revokeAllSessions(): Promise<{ count: number }> {
  try {
    const response = await apiClient.post('/auth/logout-all');
    return { count: parseInt(response.data.message?.match(/\d+/)?.[0] || '0') };
  } catch (error) {
    console.error('Failed to revoke all sessions:', error);
    throw new Error('Failed to revoke all sessions');
  }
}

/**
 * Logout current session
 */
export async function logout(): Promise<void> {
  try {
    await apiClient.post('/auth/logout');
    clearTokens();
  } catch (error) {
    console.error('Failed to logout:', error);
    // Still clear local storage even if API call fails
    clearTokens();
  }
}

// ============================================================================
// Export as service object
// ============================================================================

export const authService = {
  getSessions,
  revokeSession,
  revokeAllSessions,
  logout,
  parseUserAgent,
  formatRelativeTime,
};

export default authService;
