import { executeQuery } from '../config/database.js';
import bcrypt from 'bcryptjs';

export class AdminUser {
  constructor(data) {
    this.id = data.id;
    this.staff_email = data.staff_email;
    this.staff_id = data.staff_id;
    this.surname = data.surname;
    this.first_name = data.first_name;
    this.other_name = data.other_name;
    this.role = data.role;
    this.staff_passport = data.staff_passport;
    this.is_active = data.is_active;
    this.last_login = data.last_login;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // Get admin user by email
  static async getByEmail(email) {
    const query = `
      SELECT * FROM admin_users 
      WHERE staff_email = ? AND is_active = TRUE
    `;
    const rows = await executeQuery(query, [email]);
    return rows.length > 0 ? new AdminUser(rows[0]) : null;
  }

  // Get admin user by staff ID
  static async getByStaffId(staffId) {
    const query = `
      SELECT * FROM admin_users 
      WHERE staff_id = ? AND is_active = TRUE
    `;
    const rows = await executeQuery(query, [staffId]);
    return rows.length > 0 ? new AdminUser(rows[0]) : null;
  }

  // Verify password
  async verifyPassword(password) {
    const query = `
      SELECT password FROM admin_users 
      WHERE staff_email = ?
    `;
    const rows = await executeQuery(query, [this.staff_email]);
    if (rows.length === 0) return false;
    
    return await bcrypt.compare(password, rows[0].password);
  }

  // Update last login
  async updateLastLogin() {
    const query = `
      UPDATE admin_users 
      SET last_login = CURRENT_TIMESTAMP 
      WHERE staff_email = ?
    `;
    await executeQuery(query, [this.staff_email]);
  }

  // Create new admin user
  static async create(data) {
    const hashedPassword = await bcrypt.hash(data.password, 12);
    
    const query = `
      INSERT INTO admin_users 
      (staff_email, staff_id, surname, first_name, other_name, role, password, staff_passport) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `;
    const result = await executeQuery(query, [
      data.staff_email,
      data.staff_id,
      data.surname,
      data.first_name,
      data.other_name || null,
      data.role,
      hashedPassword,
      data.staff_passport || null
    ]);
    return result.insertId;
  }

  // Get all admin users
  static async getAll() {
    const query = `
      SELECT id, staff_email, staff_id, surname, first_name, other_name, 
             role, is_active, last_login, created_at
      FROM admin_users 
      ORDER BY created_at DESC
    `;
    const rows = await executeQuery(query);
    return rows.map(row => new AdminUser(row));
  }

  // Update admin user
  static async update(staffEmail, data) {
    const updateFields = [];
    const params = [];

    if (data.staff_email && data.staff_email !== staffEmail) {
      // Check if new email already exists
      const existingUser = await AdminUser.getByEmail(data.staff_email);
      if (existingUser) {
        throw new Error('User with this email already exists');
      }
      updateFields.push('staff_email = ?');
      params.push(data.staff_email);
    }
    if (data.staff_id) {
      // Check if new staff_id already exists
      const existingStaffId = await AdminUser.getByStaffId(data.staff_id);
      if (existingStaffId && existingStaffId.staff_email !== staffEmail) {
        throw new Error('User with this staff ID already exists');
      }
      updateFields.push('staff_id = ?');
      params.push(data.staff_id);
    }
    if (data.surname) {
      updateFields.push('surname = ?');
      params.push(data.surname);
    }
    if (data.first_name) {
      updateFields.push('first_name = ?');
      params.push(data.first_name);
    }
    if (data.other_name !== undefined) {
      updateFields.push('other_name = ?');
      params.push(data.other_name);
    }
    if (data.role) {
      updateFields.push('role = ?');
      params.push(data.role);
    }
    
    if (data.password) {
      const hashedPassword = await bcrypt.hash(data.password, 12);
      updateFields.push('password = ?');
      params.push(hashedPassword);
    }
    if (data.staff_passport !== undefined) {
      updateFields.push('staff_passport = ?');
      params.push(data.staff_passport);
    }

    if (updateFields.length === 0) {
      throw new Error('No valid fields to update');
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    params.push(staffEmail);

    const query = `
      UPDATE admin_users 
      SET ${updateFields.join(', ')}
      WHERE staff_email = ?
    `;
    await executeQuery(query, params);
  }

  // Deactivate admin user
  static async deactivate(staffEmail) {
    const query = `
      UPDATE admin_users 
      SET is_active = FALSE, updated_at = CURRENT_TIMESTAMP
      WHERE staff_email = ?
    `;
    await executeQuery(query, [staffEmail]);
  }

  // Get full name
  getFullName() {
    return `${this.surname} ${this.first_name} ${this.other_name || ''}`.trim();
  }

  // Check if user has IMTC role
  isProgramming() {
    return this.role === 'imtc';
  }

  // Check if user has bursary role
  isBursary() {
    return this.role === 'bursary';
  }
}
