const bcrypt = require('bcryptjs')
const { pool } = require('../config/db');

const login = async (req, res) => {
    const { username, password } = req.body
    
    if (!username || !password) {
        return res.status(400).json({ message: 'Username and password are required' })
    }
    
    try {
        const [users] = await pool.execute('SELECT * FROM users WHERE username = ?', [username])
        
        if (users.length === 0) {
            return res.status(401).json({ message: 'Invalid username or password' })
        }
        
        const user = users[0]
        const isPasswordValid = await bcrypt.compare(password, user.passwordHash)
        
        if (!isPasswordValid) {
            return res.status(401).json({ message: 'Invalid username or password' })
        }
        
        req.session.userId = user.userID
        req.session.username = user.username
        
        res.json({ 
            message: 'Logged in successfully', 
            userId: user.userID, 
            username: user.username 
        })
        
    } catch (error) {
        console.error('Login error:', error)
        return res.status(500).json({ message: 'Login failed', error: error.message })
    }
}

const logout = (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            console.error('Logout error:', err)
            return res.status(500).json({ message: 'Logout failed' })
        } else {
            res.json({ message: 'Logged out successfully' })
        }
    })
}

const checkSession = (req, res) => {
    if (req.session && req.session.userId) {
        res.json({ 
            authenticated: true, 
            username: req.session.username,
            userId: req.session.userId
        })
    } else {
        res.json({ authenticated: false })
    }
}

const register = async (req, res) => {
    const { username, password } = req.body
    
    console.log('Registration attempt for username:', username); // Debug log
    
    if (!username || !password) {
        console.log('Missing username or password');
        return res.status(400).json({ message: 'Username and password are required' })
    }
    
    if (password.length < 4) {
        console.log('Password too short');
        return res.status(400).json({ message: 'Password must be at least 4 characters' })
    }
    
    try {
        // Check if user already exists
        console.log('Checking if user exists...');
        const [existingUsers] = await pool.execute('SELECT * FROM users WHERE username = ?', [username])
        
        if (existingUsers.length > 0) {
            console.log('Username already exists');
            return res.status(400).json({ message: 'Username already exists' })
        }
        
        // Hash the password
        console.log('Hashing password...');
        const hashedPassword = await bcrypt.hash(password, 10)
        
        // Insert new user - CHECK THE TABLE NAME AND COLUMN NAMES
        console.log('Inserting user into database...');
        const [result] = await pool.execute(
            'INSERT INTO users (username, passwordHash) VALUES (?, ?)', 
            [username, hashedPassword]
        )
        
        console.log('User registered successfully with ID:', result.insertId);
        
        res.status(201).json({ 
            message: 'User registered successfully',
            userId: result.insertId
        })
        
    } catch (error) {
        console.error('Registration error DETAILS:', error);
        console.error('Error code:', error.code);
        console.error('Error message:', error.message);
        res.status(500).json({ message: 'Registration failed: ' + error.message })
    }
}

module.exports = { login, logout, checkSession, register }