"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loginUser = exports.registerUser = void 0;
const user_1 = require("../models/user");
const bcrypt_1 = __importDefault(require("bcrypt"));
const lodash_1 = __importDefault(require("lodash"));
/// Register a new user
const registerUser = async (req, res) => {
    const { error } = user_1.userSchema.validate(req.body);
    if (error)
        return res.status(400).json({ error: error.details[0].message });
    let user = await user_1.UserModel.findOne({ where: { email: req.body.email } });
    if (user)
        return res.status(400).json({ error: "Email already exists" });
    user = new user_1.UserModel(lodash_1.default.pick(req.body, ["name", "email", "password"]));
    const salt = await bcrypt_1.default.genSalt(10);
    user.password = await bcrypt_1.default.hash(user.password, salt);
    await user.save();
    res.status(200).json({ message: "User registered successfully" });
};
exports.registerUser = registerUser;
/// Login User
const loginUser = async (req, res) => {
    const { email, password } = req.body;
    let user = await user_1.UserModel.findOne({ where: { email } });
    if (!user)
        return res.status(400).json({ error: "Invalid email or password" });
    const validPassword = await bcrypt_1.default.compare(password, user.password);
    if (!validPassword)
        return res.status(400).json({ error: "Invalid email or password" });
    const token = (0, user_1.generateAuthToken)(user);
    res.status(200).json({ token, user: lodash_1.default.pick(user, ["id", "name", "email"]) });
};
exports.loginUser = loginUser;
