const pool = require('../config/database');

const Admin = {
  /**
   * Find admin by email
   */
  findByEmail: async (email) => {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM admin WHERE email = ?',
        [email]
      );
      return rows.length > 0 ? rows[0] : null;
    } catch (error) {
      throw new Error(`Database error: ${error.message}`);
    }
  },

  /**
   * Find admin by id
   */
  findById: async (id) => {
    try {
      const [rows] = await pool.query(
        'SELECT * FROM admin WHERE id = ?',
        [id]
      );
      return rows.length > 0 ? rows[0] : null;
    } catch (error) {
      throw new Error(`Database error: ${error.message}`);
    }
  },

  /**
   * Create new admin
   */
  create: async (name, email, hashedPassword, role = 'admin') => {
    try {
      const [result] = await pool.query(
        'INSERT INTO admin (name, email, password, role) VALUES (?, ?, ?, ?)',
        [name, email, hashedPassword, role]
      );
      return result.insertId;
    } catch (error) {
      if (error.code === 'ER_DUP_ENTRY') {
        throw new Error('Email already exists');
      }
      throw new Error(`Database error: ${error.message}`);
    }
  },

  /**
   * Update refresh token
   */
  updateRefreshToken: async (id, refreshToken) => {
    try {
      await pool.query(
        'UPDATE admin SET refresh_token = ? WHERE id = ?',
        [refreshToken, id]
      );
      return true;
    } catch (error) {
      throw new Error(`Database error: ${error.message}`);
    }
  },

  /**
   * Clear refresh token (logout)
   */
  clearRefreshToken: async (id) => {
    try {
      await pool.query(
        'UPDATE admin SET refresh_token = NULL WHERE id = ?',
        [id]
      );
      return true;
    } catch (error) {
      throw new Error(`Database error: ${error.message}`);
    }
  },

  /**
   * Get all admins
   */
  getAll: async () => {
    try {
      const [rows] = await pool.query(
        'SELECT id, name, email, role, created_at FROM admin ORDER BY created_at DESC'
      );
      return rows;
    } catch (error) {
      throw new Error(`Database error: ${error.message}`);
    }
  },
};

module.exports = Admin;
