"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserById = exports.registerUser = exports.loginUser = void 0;
const database_1 = require("../config/database");
const password_1 = require("../utils/password");
const jwt_1 = require("../utils/jwt");
const loginUser = async (email, password) => {
    const result = await (0, database_1.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 = result.rows[0];
    const isPasswordValid = await (0, password_1.comparePassword)(password, user.password);
    if (!isPasswordValid) {
        throw new Error('Invalid credentials');
    }
    const token = (0, jwt_1.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,
        },
    };
};
exports.loginUser = loginUser;
const registerUser = async (email, password, name, role = 'Agent') => {
    // Check if user already exists
    const existingUser = await (0, database_1.query)('SELECT id FROM users WHERE email = $1', [
        email,
    ]);
    if (existingUser.rows.length > 0) {
        throw new Error('User already exists');
    }
    const hashedPassword = await (0, password_1.hashPassword)(password);
    const result = await (0, database_1.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];
};
exports.registerUser = registerUser;
const getUserById = async (userId) => {
    const result = await (0, database_1.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];
};
exports.getUserById = getUserById;
