import { api } from '@/lib/api';

export interface UserProfile {
  id: number;
  name: string;
  email: string;
  phone?: string;
  email_verified_at?: string | null;
  provider?: string | null;
  created_at: string;
}

export interface UpdateProfileData {
  name?: string;
  email?: string;
  phone?: string;
  current_password?: string;
  password?: string;
  password_confirmation?: string;
}

export interface ActivitySummary {
  total_orders: number;
  pending_orders: number;
  total_reviews: number;
  total_addresses: number;
  member_since: string;
}

export interface ProfileResponse {
  user: UserProfile;
  message?: string;
}

export interface ActivityResponse {
  summary: ActivitySummary;
}

class ProfileService {
  /**
   * Get user profile
   */
  async getProfile(): Promise<UserProfile> {
    const response = await api.get<ProfileResponse>('/profile');
    return response.user;
  }

  /**
   * Update user profile with security measures
   * Includes XSS prevention and CSRF protection
   */
  async updateProfile(data: UpdateProfileData): Promise<UserProfile> {
    // Client-side sanitization (additional to server-side)
    const sanitizedData: UpdateProfileData = {};

    if (data.name) {
      // Remove any HTML tags and trim
      sanitizedData.name = data.name.replace(/<[^>]*>/g, '').trim();
    }

    if (data.email) {
      // Basic email sanitization
      sanitizedData.email = data.email.toLowerCase().trim();
    }

    if (data.phone) {
      // Remove any non-phone characters
      sanitizedData.phone = data.phone.replace(/[^0-9+\-\s()]/g, '');
    }

    // Password fields (already hashed on server)
    if (data.current_password) {
      sanitizedData.current_password = data.current_password;
    }

    if (data.password) {
      sanitizedData.password = data.password;
    }

    if (data.password_confirmation) {
      sanitizedData.password_confirmation = data.password_confirmation;
    }

    const response = await api.put<ProfileResponse>('/profile', sanitizedData);
    return response.user;
  }

  /**
   * Delete user account (requires password confirmation)
   */
  async deleteAccount(password: string): Promise<void> {
    await api.delete('/profile', {
      password,
      confirmation: 'DELETE',
    });
  }

  /**
   * Get user activity summary
   */
  async getActivitySummary(): Promise<ActivitySummary> {
    const response = await api.get<ActivityResponse>('/profile/activity');
    return response.summary;
  }

  /**
   * Validate password strength (client-side check)
   */
  validatePasswordStrength(password: string): {
    isValid: boolean;
    score: number;
    message: string;
  } {
    let score = 0;
    
    // Length check
    if (password.length >= 8) score++;
    if (password.length >= 12) score++;
    
    // Complexity checks
    if (/[a-z]/.test(password)) score++; // lowercase
    if (/[A-Z]/.test(password)) score++; // uppercase
    if (/[0-9]/.test(password)) score++; // numbers
    if (/[^a-zA-Z0-9]/.test(password)) score++; // special chars
    
    // Common password check
    const commonPasswords = ['password', '12345678', 'qwerty123', 'password123'];
    if (commonPasswords.includes(password.toLowerCase())) {
      return {
        isValid: false,
        score: 0,
        message: 'كلمة المرور ضعيفة جداً',
      };
    }

    let message = '';
    if (score < 3) message = 'ضعيفة';
    else if (score < 5) message = 'متوسطة';
    else message = 'قوية';

    return {
      isValid: score >= 3,
      score,
      message,
    };
  }

  /**
   * Sanitize user input to prevent XSS
   */
  sanitizeInput(input: string): string {
    return input
      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
      .replace(/<[^>]*>/g, '')
      .trim();
  }
}

export const profileService = new ProfileService();
