import { query } from '../config/database';
import { hashPassword, comparePassword } from '../utils/password';
import { generateToken } from '../utils/jwt';

interface User {
    id: number;
    email: string;
    password: string;
    name: string;
    role: string;
}

export const loginUser = async (email: string, password: string) => {
    const result = await query(
        'SELECT id, email, password, name, role FROM users WHERE email = $1',
        [email]
    );

    if (result.rows.length === 0) {
        throw new Error('Invalid credentials');
    }

    const user: User = result.rows[0];
    const isPasswordValid = await comparePassword(password, user.password);

    if (!isPasswordValid) {
        throw new Error('Invalid credentials');
    }

    const token = generateToken({
        userId: user.id,
        email: user.email,
        role: user.role,
    });

    return {
        token,
        user: {
            id: user.id,
            email: user.email,
            name: user.name,
            role: user.role,
        },
    };
};

export const registerUser = async (
    email: string,
    password: string,
    name: string,
    role: string = 'Agent'
) => {
    // Check if user already exists
    const existingUser = await query('SELECT id FROM users WHERE email = $1', [
        email,
    ]);

    if (existingUser.rows.length > 0) {
        throw new Error('User already exists');
    }

    const hashedPassword = await hashPassword(password);

    const result = await query(
        'INSERT INTO users (email, password, name, role, created_at) VALUES ($1, $2, $3, $4, NOW()) RETURNING id, email, name, role',
        [email, hashedPassword, name, role]
    );

    return result.rows[0];
};

export const getUserById = async (userId: number) => {
    const result = await query(
        'SELECT id, email, name, role, created_at FROM users WHERE id = $1',
        [userId]
    );

    if (result.rows.length === 0) {
        throw new Error('User not found');
    }

    return result.rows[0];
};
