'use strict'

const { execute, queryOne, query } = require('../database/postgres')

class Admin {
  static findAll() {
    return query('SELECT id, username, nome, email, telefone, created_at FROM admins ORDER BY id ASC')
  }

  static findById(id) {
    return queryOne('SELECT * FROM admins WHERE id = $1', [id])
  }

  static findByUsername(username) {
    return queryOne('SELECT * FROM admins WHERE username = $1', [username])
  }

  static create(username, password_hash) {
    return execute(
      'INSERT INTO admins (username, password_hash) VALUES ($1, $2) RETURNING id',
      [username, password_hash]
    )
  }

  static update(id, data) {
    const fields = []
    const values = []
    let i = 1

    if (data.username)      { fields.push(`username = $${i++}`);      values.push(data.username) }
    if (data.password_hash) { fields.push(`password_hash = $${i++}`); values.push(data.password_hash) }
    if ('nome'     in data) { fields.push(`nome = $${i++}`);     values.push(data.nome) }
    if ('email'    in data) { fields.push(`email = $${i++}`);    values.push(data.email) }
    if ('telefone' in data) { fields.push(`telefone = $${i++}`); values.push(data.telefone) }

    if (!fields.length) return Promise.resolve({ rowCount: 0 })
    values.push(id)
    return execute(`UPDATE admins SET ${fields.join(', ')} WHERE id = $${i}`, values)
  }

  static delete(id) {
    return execute('DELETE FROM admins WHERE id = $1', [id])
  }

  static async count() {
    const row = await queryOne('SELECT COUNT(*) as total FROM admins')
    return parseInt(row?.total || 0)
  }
}

module.exports = Admin
