// Local API service to handle authentication
import { API_BASE_URL } from '../config/apiConfig';

// Generate a random token as fallback if API fails
const generateToken = (length = 32) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let token = '';
  for (let i = 0; i < length; i++) {
    token += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return token;
};

interface LoginResponse {
  success: boolean;
  token?: string;
  error?: string;
  user?: {
    id?: number;
    name: string;
    email: string;
    role: string;
  };
}

// Demo users for fallback if database connection fails
const FALLBACK_USERS = [
  {
    email: 'admin@example.com',
    // This is a SHA-256 hash of 'admin123'
    passwordHash: '240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9',
    name: 'Admin User',
    role: 'admin',
  },
  {
    email: 'user@example.com',
    // This is a SHA-256 hash of 'user123'
    passwordHash: 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3',
    name: 'Regular User',
    role: 'user',
  }
];

// Login function that uses MySQL database via API
export const localLogin = async (email: string, hashedPassword: string): Promise<LoginResponse> => {
  try {
    console.log('Attempting to login with database:', email);
    
    // Call the login API endpoint
    const response = await fetch(`${API_BASE_URL}/api/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
      body: JSON.stringify({ email, password: hashedPassword }),
      credentials: 'include',
    });

    // Parse the API response
    const result = await response.json();
    
    if (response.ok && result.success) {
      console.log('Database login successful for:', email);
      return result;
    }
    
    console.warn('Database login failed, error:', result.error);
    console.warn('Falling back to demo users...');
    
    // If API call fails, fall back to demo users
    return fallbackLogin(email, hashedPassword);
  } catch (error) {
    console.error('API login error, falling back to demo users:', error);
    return fallbackLogin(email, hashedPassword);
  }
};

// Fallback login function using demo users
const fallbackLogin = async (email: string, hashedPassword: string): Promise<LoginResponse> => {
  // Simulate network delay
  await new Promise(resolve => setTimeout(resolve, 800));
  
  // Find user with matching email
  const user = FALLBACK_USERS.find(u => u.email === email);
  
  if (!user) {
    return { 
      success: false, 
      error: 'User not found' 
    };
  }
  
  // Check password hash
  if (user.passwordHash !== hashedPassword) {
    return { 
      success: false, 
      error: 'Invalid credentials' 
    };
  }
  
  // Generate authentication token
  const token = generateToken();
  
  console.log('Fallback login successful for demo user:', user.email);
  
  // Return successful login response
  return {
    success: true,
    token,
    user: {
      name: user.name,
      email: user.email,
      role: user.role
    }
  };
};