const bcrypt = require('bcryptjs');
const db = require('../models');
const generateToken = require('../utils/jwtHelper');

const User = db.User;

const registerUser = async (req, res, next) => {
    try {
        // Extract fullName
        const { email, password, role, fullName } = req.body;

        const userExists = await User.findOne({ where: { email } });
        if (userExists) {
            return res.status(400).json({ message: 'User already exists' });
        }

        const salt = await bcrypt.genSalt(10);
        const passwordHash = await bcrypt.hash(password, salt);

        const user = await User.create({
            email,
            passwordHash,
            role,
            fullName // Save it!
        });

        res.status(201).json({
            id: user.id,
            email: user.email,
            role: user.role,
            fullName: user.fullName,
            token: generateToken(user.id)
        });
    } catch (error) {
        next(error);
    }
};

const loginUser = async (req, res, next) => {
    try {
        const { email, password } = req.body;

        const user = await User.findOne({ 
            where: { email },
            include: [
                { model: db.EmployerProfile, as: 'employerProfile' },
                { model: db.JobSeekerProfile, as: 'jobSeekerProfile' }
            ]
        });

        if (user && (await bcrypt.compare(password, user.passwordHash))) {
            const profileData = user.role === 'Employer' ? user.employerProfile : user.jobSeekerProfile;
            
            res.json({
                id: user.id,
                email: user.email,
                role: user.role,
                fullName: user.fullName || profileData?.fullName || profileData?.companyName, 
                companyName: profileData?.companyName,
                cvUrl: profileData?.cvUrl,
                token: generateToken(user.id),
            });
        } else {
            res.status(401).json({ message: 'Invalid email or password' });
        }
    } catch (error) {
        next(error);
    }
};

module.exports = { registerUser, loginUser };