const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { body, validationResult } = require('express-validator');
const database = require('../config/database');
const { JWT_SECRET, auth } = require('../middleware/auth');

// Register new user
router.post('/register',
    [
        body('email').isEmail().normalizeEmail(),
        body('password').isLength({ min: 8 }),
        body('first_name').trim().notEmpty(),
        body('last_name').trim().notEmpty(),
        body('phone').optional().trim()
    ],
    async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(400).json({ errors: errors.array() });
            }

            const { email, password, first_name, last_name, phone } = req.body;

            // Check if user already exists
            const existingUser = await database.get(
                'SELECT id FROM users WHERE email = ?',
                [email]
            );

            if (existingUser) {
                return res.status(400).json({ error: 'Email already registered' });
            }

            // Hash password
            const hashedPassword = await bcrypt.hash(password, 10);

            // Create user
            const result = await database.run(
                `INSERT INTO users (email, password, first_name, last_name, phone, role, is_verified) 
                 VALUES (?, ?, ?, ?, ?, 'customer', 1)`,
                [email, hashedPassword, first_name, last_name, phone || null]
            );

            // Generate JWT token
            const token = jwt.sign(
                { 
                    id: result.id, 
                    email, 
                    role: 'customer',
                    first_name,
                    last_name
                },
                JWT_SECRET,
                { expiresIn: '7d' }
            );

            res.status(201).json({
                message: 'Registration successful',
                token,
                user: {
                    id: result.id,
                    email,
                    first_name,
                    last_name,
                    role: 'customer'
                }
            });
        } catch (error) {
            console.error('Register error:', error);
            res.status(500).json({ error: 'Registration failed' });
        }
    }
);

// Login
router.post('/login',
    [
        body('email').isEmail().normalizeEmail(),
        body('password').notEmpty()
    ],
    async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                console.log('Validation errors:', errors.array());
                return res.status(400).json({ errors: errors.array() });
            }

            const { email, password } = req.body;
            console.log('Login attempt:', email);

            // Find user
            const user = await database.get(
                'SELECT * FROM users WHERE email = ?',
                [email]
            );

            console.log('User found:', user ? `Yes (${user.email})` : 'No');

            if (!user) {
                return res.status(401).json({ error: 'Invalid email or password' });
            }

            // Verify password
            const isValidPassword = await bcrypt.compare(password, user.password);
            console.log('Password valid:', isValidPassword);
            
            if (!isValidPassword) {
                return res.status(401).json({ error: 'Invalid email or password' });
            }

            // Generate JWT token
            const token = jwt.sign(
                { 
                    id: user.id, 
                    email: user.email, 
                    role: user.role,
                    first_name: user.first_name,
                    last_name: user.last_name
                },
                JWT_SECRET,
                { expiresIn: '7d' }
            );

            res.json({
                message: 'Login successful',
                token,
                user: {
                    id: user.id,
                    email: user.email,
                    first_name: user.first_name,
                    last_name: user.last_name,
                    phone: user.phone,
                    role: user.role,
                    is_first_booking: user.is_first_booking
                }
            });
        } catch (error) {
            console.error('Login error:', error);
            res.status(500).json({ error: 'Login failed' });
        }
    }
);

// Verify token
router.get('/verify', auth, async (req, res) => {
    try {
        // If the auth middleware passes, token is valid
        res.json({ 
            valid: true,
            user: {
                id: req.user.id,
                email: req.user.email,
                role: req.user.role,
                first_name: req.user.first_name,
                last_name: req.user.last_name
            }
        });
    } catch (error) {
        console.error('Verify token error:', error);
        res.status(500).json({ error: 'Token verification failed' });
    }
});

// Get current user
router.get('/me', auth, async (req, res) => {
    try {
        const user = await database.get(
            'SELECT id, email, first_name, last_name, phone, role, is_first_booking, created_at FROM users WHERE id = ?',
            [req.user.id]
        );

        if (!user) {
            return res.status(404).json({ error: 'User not found' });
        }

        res.json({ user });
    } catch (error) {
        console.error('Get user error:', error);
        res.status(500).json({ error: 'Failed to fetch user' });
    }
});

// Update profile
router.put('/profile', auth,
    [
        body('first_name').optional().trim().notEmpty(),
        body('last_name').optional().trim().notEmpty(),
        body('phone').optional().trim()
    ],
    async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(400).json({ errors: errors.array() });
            }

            const { first_name, last_name, phone } = req.body;
            const updates = [];
            const values = [];

            if (first_name) {
                updates.push('first_name = ?');
                values.push(first_name);
            }
            if (last_name) {
                updates.push('last_name = ?');
                values.push(last_name);
            }
            if (phone !== undefined) {
                updates.push('phone = ?');
                values.push(phone);
            }

            if (updates.length === 0) {
                return res.status(400).json({ error: 'No fields to update' });
            }

            updates.push('updated_at = CURRENT_TIMESTAMP');
            values.push(req.user.id);

            await database.run(
                `UPDATE users SET ${updates.join(', ')} WHERE id = ?`,
                values
            );

            const updatedUser = await database.get(
                'SELECT id, email, first_name, last_name, phone, role FROM users WHERE id = ?',
                [req.user.id]
            );

            res.json({
                message: 'Profile updated successfully',
                user: updatedUser
            });
        } catch (error) {
            console.error('Update profile error:', error);
            res.status(500).json({ error: 'Failed to update profile' });
        }
    }
);

// Change password
router.put('/change-password', auth,
    [
        body('current_password').notEmpty(),
        body('new_password').isLength({ min: 8 })
    ],
    async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(400).json({ errors: errors.array() });
            }

            const { current_password, new_password } = req.body;

            // Get user with password
            const user = await database.get(
                'SELECT password FROM users WHERE id = ?',
                [req.user.id]
            );

            // Verify current password
            const isValid = await bcrypt.compare(current_password, user.password);
            if (!isValid) {
                return res.status(401).json({ error: 'Current password is incorrect' });
            }

            // Hash new password
            const hashedPassword = await bcrypt.hash(new_password, 10);

            // Update password
            await database.run(
                'UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
                [hashedPassword, req.user.id]
            );

            res.json({ message: 'Password changed successfully' });
        } catch (error) {
            console.error('Change password error:', error);
            res.status(500).json({ error: 'Failed to change password' });
        }
    }
);

module.exports = router;
