// lib/admin-api.ts - CLIENT-SAFE VERSION (NO PRISMA DIRECT CALLS)
import bcrypt from 'bcryptjs'

// Helper function to handle API responses consistently
async function handleApiResponse(response: Response, customErrorMessage?: string) {
  if (!response.ok) {
    let errorData = null;
    let responseText = '';
    
    try {
      // Try to get the response as text first
      responseText = await response.text();
      console.log(`API Error (${response.status}):`, responseText);
      
      // Try to parse as JSON if it's not empty
      if (responseText && responseText.trim()) {
        try {
          errorData = JSON.parse(responseText);
        } catch (jsonError) {
          // Not JSON, treat as plain text
          errorData = { message: responseText };
        }
      } else {
        errorData = { message: `Server returned ${response.status} ${response.statusText}` };
      }
    } catch (e) {
      console.error('Failed to read response body:', e);
      errorData = { message: `HTTP ${response.status}: ${response.statusText}` };
    }
    
    // Create a meaningful error message
    let errorMessage = customErrorMessage || 'Request failed';
    
    if (errorData?.error) {
      errorMessage = errorData.error;
    } else if (errorData?.message) {
      errorMessage = errorData.message;
    } else if (response.status === 409) {
      errorMessage = errorData?.details || 'Resource already exists';
    } else if (response.status === 400) {
      errorMessage = errorData?.details || 'Invalid request data';
    } else if (response.status === 401) {
      errorMessage = 'Unauthorized. Please login again.';
    } else if (response.status === 403) {
      errorMessage = 'Forbidden. You don\'t have permission to perform this action.';
    } else if (response.status === 404) {
      errorMessage = 'Resource not found';
    } else if (response.status === 500) {
      errorMessage = 'Server error. Please try again later.';
    }
    
    // Create enhanced error object
    const error = new Error(errorMessage);
    (error as any).response = {
      data: errorData,
      status: response.status,
      statusText: response.statusText
    };
    
    throw error;
  }
  
  return response.json();
}

// Department functions
export async function fetchDepartments() {
  const response = await fetch('/api/admin/departments')
  return handleApiResponse(response, 'Failed to fetch departments')
}

export async function createDepartment(data: { name: string; code: string; description?: string }) {
  const response = await fetch('/api/admin/departments', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  })
  return handleApiResponse(response, 'Failed to create department')
}

export async function updateDepartment(deptId: string, updates: { name?: string; code?: string; description?: string; isActive?: boolean }) {
  const response = await fetch(`/api/admin/departments/${deptId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updates)
  })
  return handleApiResponse(response, 'Failed to update department')
}

// Employee functions
export async function fetchAllEmployees() {
  const response = await fetch('/api/admin/employees')
  return handleApiResponse(response, 'Failed to fetch employees')
}

// User functions
export async function fetchUsers() {
  const response = await fetch('/api/admin/users')
  return handleApiResponse(response, 'Failed to fetch users')
}

export async function createUser(userData: {
  username: string;
  password_hash: string;
  email: string;
  name: string;
  role: string;
  employee_id?: string;
  dept?: string;
  position?: string;
  gender?: string;
  is_intern?: boolean;
}) {
  const response = await fetch('/api/admin/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData)
  })
  return handleApiResponse(response, 'Failed to create user')
}

export async function updateUser(userId: string, updates: Record<string, unknown>) {
  const response = await fetch(`/api/admin/users/${userId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updates)
  })
  return handleApiResponse(response, 'Failed to update user')
}

export async function deactivateUser(userId: string) {
  const response = await fetch(`/api/admin/users/${userId}`, {
    method: 'DELETE'
  })
  return handleApiResponse(response, 'Failed to deactivate user')
}

export async function resetUserPassword(userId: string, newHash: string, resetBy: string) {
  const response = await fetch(`/api/admin/users/${userId}/reset-password`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ newHash, resetBy })
  })
  return handleApiResponse(response, 'Failed to reset password')
}

// HOD functions
export async function createHODWithUser(params: {
  fullName: string;
  email: string;
  phone?: string;
  dept: string;
  username: string;
  initialPassword: string;
  assignedByName: string;
}) {
  const response = await fetch('/api/admin/hod', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params)
  })
  return handleApiResponse(response, 'Failed to create HOD')
}

export async function assignHODToDepartment(deptName: string, hodUserId: string, assignedByName: string) {
  const response = await fetch('/api/admin/hod/assign', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ deptName, hodUserId, assignedByName })
  })
  return handleApiResponse(response, 'Failed to assign HOD')
}

export async function promoteEmployee(params: {
  employeeId: string;
  employeeName: string;
  fromRole: string;
  toRole: string;
  fromDept?: string;
  toDept?: string;
  authorizedByName: string;
  notes?: string;
}) {
  const response = await fetch('/api/admin/promote', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params)
  })
  return handleApiResponse(response, 'Failed to promote employee')
}

// Employee creation with user - ENHANCED ERROR HANDLING
export async function createEmployeeWithUser(params: {
  fullName: string;
  email: string;
  phone?: string;
  gender?: string;
  dept: string;
  position: string;
  joinDate: string;
  salary?: string;
  employmentType: string;
  createdByName: string;
  dob?: string;
  nationalId?: string;
  kraPin?: string;
}) {
  console.log('📤 Sending employee creation request:', {
    fullName: params.fullName,
    email: params.email,
    dept: params.dept,
    position: params.position,
    hasNationalId: !!params.nationalId,
    hasKraPin: !!params.kraPin
  });
  
  const response = await fetch('/api/admin/employees/with-user', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params)
  });
  
  // Handle non-200 responses with detailed error parsing
  if (!response.ok) {
    let errorData = null;
    let responseText = '';
    
    try {
      // Get raw response text
      responseText = await response.text();
      console.log(`🔴 API Error Response (${response.status}):`, responseText);
      
      // Try to parse as JSON
      if (responseText && responseText.trim()) {
        try {
          errorData = JSON.parse(responseText);
        } catch (jsonError) {
          // Not JSON - use as plain text message
          errorData = { message: responseText, raw: true };
        }
      } else {
        errorData = { message: `Server returned ${response.status} ${response.statusText}` };
      }
    } catch (e) {
      console.error('Failed to read response body:', e);
      errorData = { message: `HTTP ${response.status}: ${response.statusText}` };
    }
    
    // Build user-friendly error message based on status code and response
    let errorMessage = '';
    
    if (response.status === 409) {
      // Conflict - check for specific conflicts
      if (errorData?.conflict === 'email' || errorData?.field === 'email') {
        errorMessage = `❌ Email "${params.email}" is already registered in the system.\n\nThis email belongs to: ${errorData?.existingName || 'another employee'}\n\n💡 Please use a different email address.`;
      } else if (errorData?.conflict === 'nationalId' || errorData?.field === 'nationalId') {
        errorMessage = `❌ National ID "${params.nationalId}" is already registered.\n\nThis ID belongs to: ${errorData?.existingName || 'another employee'}\n\n💡 Please verify the National ID number.`;
      } else if (errorData?.conflict === 'kraPin' || errorData?.field === 'kraPin') {
        errorMessage = `❌ KRA PIN "${params.kraPin}" is already registered.\n\nThis PIN belongs to: ${errorData?.existingName || 'another employee'}\n\n💡 Please verify the KRA PIN.`;
      } else if (errorData?.conflict === 'user') {
        errorMessage = `❌ Email "${params.email}" is already registered as a system user.\n\n💡 Please use a different email address or check if this user is already an employee.`;
      } else if (errorData?.conflict === 'employee') {
        errorMessage = `❌ Employee with email "${params.email}" already exists.\n\nEmployee: ${errorData?.existingName || 'Unknown'} (ID: ${errorData?.existingId || 'N/A'})\nStatus: ${errorData?.existingStatus || 'Unknown'}\n\n💡 Please use a different email address.`;
      } else {
        errorMessage = `❌ Cannot create employee: A record with this email "${params.email}" or identification number already exists.\n\n💡 Please check if this employee has already been registered.`;
      }
    } else if (response.status === 400) {
      // Bad request - validation errors
      if (errorData?.missingFields && errorData.missingFields.length > 0) {
        errorMessage = `❌ Missing required fields:\n• ${errorData.missingFields.join('\n• ')}\n\n💡 Please fill in all required fields.`;
      } else if (errorData?.invalidFields && errorData.invalidFields.length > 0) {
        errorMessage = `❌ Invalid data in fields:\n• ${errorData.invalidFields.join('\n• ')}\n\n💡 Please check the format of your inputs.`;
      } else {
        errorMessage = `❌ Invalid request data: ${errorData?.message || 'Please check all fields and try again.'}`;
      }
    } else if (response.status === 401) {
      errorMessage = `❌ Unauthorized: Your session may have expired.\n\n💡 Please refresh the page and try again.`;
    } else if (response.status === 403) {
      errorMessage = `❌ Forbidden: You don't have permission to add employees.\n\n💡 Contact your system administrator.`;
    } else if (response.status === 500) {
      errorMessage = `❌ Server error occurred.\n\n${errorData?.message || 'Please try again later or contact support.'}\n\n💡 Check that your database is connected and tables exist.`;
    } else {
      errorMessage = errorData?.message || errorData?.error || `Error ${response.status}: Failed to create employee`;
    }
    
    // Create enhanced error object with full details
    const error = new Error(errorMessage);
    (error as any).response = {
      data: errorData,
      status: response.status,
      statusText: response.statusText
    };
    (error as any).conflict = errorData?.conflict || errorData?.field;
    (error as any).existingData = errorData?.existingData;
    
    // Log detailed error for debugging
    console.error('🚨 Enhanced API Error:', {
      status: response.status,
      statusText: response.statusText,
      conflict: errorData?.conflict,
      message: errorMessage,
      fullData: errorData
    });
    
    throw error;
  }
  
  // Success - parse and return JSON
  const result = await response.json();
  console.log('✅ Employee created successfully:', {
    empNumber: result.empNumber,
    username: result.username,
    emailSent: result.emailSent
  });
  
  // Log credentials to console (no actual email sending)
  console.log('========================================');
  console.log('📧 EMPLOYEE CREDENTIALS');
  console.log('========================================');
  console.log(`To: ${result.email || params.email}`);
  console.log(`Name: ${result.fullName || params.fullName}`);
  console.log(`Username: ${result.username}`);
  console.log(`Password: ${result.tempPassword}`);
  console.log(`Role: employee`);
  console.log(`Department: ${params.dept}`);
  console.log('========================================');
  console.log('⚠️ Email not sent - SMTP not configured');
  console.log('========================================');
  
  return result;
}

// Password utilities
export async function hashPassword(password: string): Promise<string> {
  return await bcrypt.hash(password, 10)
}

export function generateTempPassword(username: string): string {
  const year = new Date().getFullYear()
  return `${username}@${year}`
}

// Email function - Just logs to console (no actual email sending)
export async function sendWelcomeEmail(params: {
  to: string;
  name: string;
  username: string;
  password: string;
  role: string;
  dept?: string;
}): Promise<{ emailSent: boolean; message: string }> {
  console.log('========================================');
  console.log('📧 WELCOME EMAIL (Development Mode)');
  console.log('========================================');
  console.log(`To: ${params.to}`);
  console.log(`Name: ${params.name}`);
  console.log(`Username: ${params.username}`);
  console.log(`Password: ${params.password}`);
  console.log(`Role: ${params.role}`);
  console.log(`Department: ${params.dept || 'N/A'}`);
  console.log('========================================');
  console.log('⚠️ Email is NOT actually sent - configure SMTP to send real emails');
  console.log('========================================');
  
  return { emailSent: false, message: 'Email not sent - configure SMTP in .env.local' }
}