const dbManager = require('../database/DatabaseManager');

class AdminUserRepository {
    async countActiveAdmins() {
        const row = await dbManager.get(
            'SELECT COUNT(*) as count FROM admin_users WHERE is_active = 1'
        );
        return row ? row.count : 0;
    }

    async getByUsername(username) {
        return dbManager.get(
            'SELECT * FROM admin_users WHERE username = ?',
            [username]
        );
    }

    async getById(id) {
        return dbManager.get(
            'SELECT * FROM admin_users WHERE id = ?',
            [id]
        );
    }

    async listActiveAdmins() {
        return dbManager.all(
            `SELECT id, username, role, is_active, requires_password_change, last_login_at, created_at, updated_at
             FROM admin_users
             WHERE is_active = 1
             ORDER BY username ASC`
        );
    }

    async createAdminUser({ username, passwordHash, role = 'admin', requiresPasswordChange = false }) {
        const result = await dbManager.run(
            `INSERT INTO admin_users (username, password_hash, role, requires_password_change)
             VALUES (?, ?, ?, ?)` ,
            [username, passwordHash, role, requiresPasswordChange ? 1 : 0]
        );
        return result.id;
    }

    async updatePassword(id, newPasswordHash, requiresPasswordChange = false) {
        await dbManager.run(
            `UPDATE admin_users
             SET password_hash = ?, requires_password_change = ?
             WHERE id = ?`,
            [newPasswordHash, requiresPasswordChange ? 1 : 0, id]
        );
    }

    async markInactive(id) {
        await dbManager.run(
            'UPDATE admin_users SET is_active = 0 WHERE id = ?',
            [id]
        );
    }

    async recordSuccessfulLogin(id) {
        await dbManager.run(
            'UPDATE admin_users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?',
            [id]
        );
    }
}

module.exports = new AdminUserRepository();
