"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteUser = exports.updateUser = exports.getUserById = exports.getAllUsers = void 0;
const database_1 = require("../config/database");
const getAllUsers = async () => {
    const result = await (0, database_1.query)('SELECT id, email, name, role, created_at FROM users ORDER BY created_at DESC');
    return result.rows;
};
exports.getAllUsers = getAllUsers;
const getUserById = async (id) => {
    const result = await (0, database_1.query)('SELECT id, email, name, role, created_at FROM users WHERE id = $1', [id]);
    if (result.rows.length === 0) {
        throw new Error('User not found');
    }
    return result.rows[0];
};
exports.getUserById = getUserById;
const updateUser = async (id, data) => {
    const fields = [];
    const values = [];
    let paramIndex = 1;
    if (data.name) {
        fields.push(`name = $${paramIndex++}`);
        values.push(data.name);
    }
    if (data.email) {
        fields.push(`email = $${paramIndex++}`);
        values.push(data.email);
    }
    if (data.role) {
        fields.push(`role = $${paramIndex++}`);
        values.push(data.role);
    }
    if (fields.length === 0) {
        throw new Error('No fields to update');
    }
    values.push(id);
    const result = await (0, database_1.query)(`UPDATE users SET ${fields.join(', ')} WHERE id = $${paramIndex} RETURNING id, email, name, role, created_at`, values);
    if (result.rows.length === 0) {
        throw new Error('User not found');
    }
    return result.rows[0];
};
exports.updateUser = updateUser;
const deleteUser = async (id) => {
    const result = await (0, database_1.query)('DELETE FROM users WHERE id = $1 RETURNING id', [
        id,
    ]);
    if (result.rows.length === 0) {
        throw new Error('User not found');
    }
    return { message: 'User deleted successfully' };
};
exports.deleteUser = deleteUser;
