import { pool } from '../config/db.js';
import bcrypt from 'bcryptjs';

export const Admin = {
  async findByEmail(email) {
    const [rows] = await pool.query('SELECT * FROM admins WHERE email = :email LIMIT 1', {
      email,
    });
    return rows[0] || null;
  },

  async findById(id) {
    const [rows] = await pool.query(
      'SELECT id, name, email, created_at FROM admins WHERE id = :id LIMIT 1',
      { id }
    );
    return rows[0] || null;
  },

  async create({ name, email, password }) {
    const password_hash = await bcrypt.hash(password, 12);
    const [result] = await pool.query(
      'INSERT INTO admins (name, email, password_hash) VALUES (:name, :email, :password_hash)',
      { name, email, password_hash }
    );
    return this.findById(result.insertId);
  },

  async verifyPassword(admin, plainPassword) {
    return bcrypt.compare(plainPassword, admin.password_hash);
  },

  async findByResetTokenHash(tokenHash) {
    const [rows] = await pool.query(
      `SELECT * FROM admins
       WHERE reset_token_hash = :tokenHash AND reset_token_expires_at > NOW()
       LIMIT 1`,
      { tokenHash }
    );
    return rows[0] || null;
  },

  async setResetToken(id, { tokenHash, expiresAt }) {
    await pool.query(
      'UPDATE admins SET reset_token_hash = :tokenHash, reset_token_expires_at = :expiresAt WHERE id = :id',
      { id, tokenHash, expiresAt }
    );
  },

  async updatePassword(id, newPassword) {
    const password_hash = await bcrypt.hash(newPassword, 12);
    await pool.query(
      `UPDATE admins
       SET password_hash = :password_hash, reset_token_hash = NULL, reset_token_expires_at = NULL
       WHERE id = :id`,
      { id, password_hash }
    );
  },

  async findAll() {
    const [rows] = await pool.query('SELECT id, name, email, created_at FROM admins ORDER BY created_at');
    return rows;
  },

  async count() {
    const [rows] = await pool.query('SELECT COUNT(*) AS count FROM admins');
    return rows[0].count;
  },

  async updateProfile(id, { name, email }) {
    await pool.query('UPDATE admins SET name = :name, email = :email WHERE id = :id', {
      id,
      name,
      email,
    });
    return this.findById(id);
  },

  async delete(id) {
    const [result] = await pool.query('DELETE FROM admins WHERE id = :id', { id });
    return result.affectedRows > 0;
  },
};
