const { getConnection } = require('../config/database');
const bcrypt = require('bcryptjs');

class Admin {
  static async findByUsername(username) {
    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT * FROM admins WHERE username = ?',
      [username]
    );
    return rows[0];
  }

  static async findByEmail(email) {
    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT * FROM admins WHERE email = ?',
      [email]
    );
    return rows[0];
  }

  static async findById(id) {
    const connection = getConnection();
    const [rows] = await connection.execute(
      'SELECT id, username, email, created_at FROM admins WHERE id = ?',
      [id]
    );
    return rows[0];
  }

  static async create(adminData) {
    const connection = getConnection();
    const { username, email, password } = adminData;
    
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const [result] = await connection.execute(
      'INSERT INTO admins (username, email, password) VALUES (?, ?, ?)',
      [username, email, hashedPassword]
    );
    
    return await this.findById(result.insertId);
  }

  static async verifyPassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
  }
}

module.exports = Admin;