const express = require('express');
const jwt = require('jsonwebtoken');
const User = require('../models/User');

const router = express.Router();

/**
 * @route   POST /api/auth/register
 * @desc    Register a new user
 * @access  Public
 */
router.post('/register', async (req, res) => {
    try {
        const { fullName, email, username, password, agreedToRules } = req.body;

        // Kiểm tra thông tin bắt buộc
        if (!fullName || !email || !username || !password || agreedToRules === undefined) {
            return res.status(400).json({ message: 'Vui lòng cung cấp đầy đủ thông tin đăng ký' });
        }

        // Kiểm tra xem username hoặc email đã tồn tại chưa
        const userExists = await User.findOne({ $or: [{ username }, { email }] });
        if (userExists) {
            const field = userExists.username === username ? 'Tên đăng nhập' : 'Email';
            return res.status(400).json({ message: `${field} đã được sử dụng` });
        }

        // Check if this is the very first user registering
        const userCount = await User.countDocuments();
        let finalRole = 'user';

        if (userCount === 0) {
            // First user to register in the system gets the supreme admin role
            finalRole = 'admin';
        }

        const user = new User({
            fullName,
            email,
            username,
            password,
            agreedToRules,
            role: finalRole
        });

        await user.save();

        res.status(201).json({
            message: 'User registered successfully',
            user: {
                id: user._id,
                username: user.username,
                role: user.role
            }
        });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

/**
 * @route   POST /api/auth/login
 * @desc    Authenticate user & get token
 * @access  Public
 */
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        const user = await User.findOne({ username });
        if (!user || !(await user.comparePassword(password))) {
            return res.status(401).json({ message: 'Invalid credentials' });
        }

        // Generate JWT
        const token = jwt.sign(
            { id: user._id, role: user.role },
            process.env.JWT_SECRET,
            { expiresIn: '30d' }
        );

        res.json({
            token,
            user: {
                id: user._id,
                username: user.username,
                role: user.role
            }
        });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

module.exports = router;
