import { query } from '../config/database';
import { hashPassword } from '../utils/password';

export const getAllUsers = async () => {
    const result = await query(
        'SELECT id, email, name, role, created_at FROM users ORDER BY created_at DESC'
    );
    return result.rows;
};

export const getUserById = async (id: number) => {
    const result = await 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];
};

export const updateUser = async (
    id: number,
    data: { name?: string; email?: string; role?: string }
) => {
    const fields: string[] = [];
    const values: any[] = [];
    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 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];
};

export const deleteUser = async (id: number) => {
    const result = await 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' };
};
