const nocodbService = require('../services/nocodb');
const logger = require('../utils/logger');
const { extractId } = require('../utils/helpers');

class AuthController {
    async login(req, res) {
        try {
            const { email, password } = req.body;
            
            // Validate input
            if (!email || !password) {
                return res.status(400).json({
                    success: false,
                    error: 'Email and password are required'
                });
            }
            
            // Validate email format
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                return res.status(400).json({
                    success: false,
                    error: 'Invalid email format'
                });
            }
            
            logger.info('Login attempt:', {
                email,
                ip: req.ip,
                cfIp: req.headers['cf-connecting-ip'],
                userAgent: req.headers['user-agent']
            });
            
            // Fetch user from NocoDB
            const user = await nocodbService.getUserByEmail(email);
            
            if (!user) {
                logger.warn(`No user found with email: ${email}`);
                return res.status(401).json({
                    success: false,
                    error: 'Invalid email or password'
                });
            }
            
            // Check password
            if (user.Password !== password && user.password !== password) {
                logger.warn(`Invalid password for email: ${email}`);
                return res.status(401).json({
                    success: false,
                    error: 'Invalid email or password'
                });
            }
            
            // Update last login time
            try {
                const userId = extractId(user);
                await nocodbService.update(
                    require('../config').nocodb.loginSheetId,
                    userId,
                    {
                        'Last Login': new Date().toISOString(),
                        last_login: new Date().toISOString()
                    }
                );
            } catch (updateError) {
                logger.warn('Failed to update last login time:', updateError.message);
                // Don't fail the login
            }
            
            // Set session
            req.session.authenticated = true;
            req.session.userEmail = email;
            req.session.userName = user.Name || user.name || email;
            req.session.isAdmin = user.Admin === true || user.Admin === 1 || 
                                 user.admin === true || user.admin === 1;
            req.session.userId = extractId(user);
            
            // Force session save
            req.session.save((err) => {
                if (err) {
                    logger.error('Session save error:', err);
                    return res.status(500).json({
                        success: false,
                        error: 'Session error. Please try again.'
                    });
                }
                
                logger.info(`User authenticated: ${email}, Admin: ${req.session.isAdmin}`);
                
                res.json({
                    success: true,
                    message: 'Login successful',
                    user: {
                        email: email,
                        name: req.session.userName,
                        isAdmin: req.session.isAdmin
                    }
                });
            });
            
        } catch (error) {
            logger.error('Login error:', error.message);
            res.status(500).json({
                success: false,
                error: 'Authentication service error. Please try again later.'
            });
        }
    }
    
    async logout(req, res) {
        req.session.destroy((err) => {
            if (err) {
                logger.error('Logout error:', err);
                return res.status(500).json({
                    success: false,
                    error: 'Logout failed'
                });
            }
            res.json({
                success: true,
                message: 'Logged out successfully'
            });
        });
    }
    
    async check(req, res) {
        res.json({
            authenticated: req.session?.authenticated || false,
            user: req.session?.authenticated ? {
                email: req.session.userEmail,
                name: req.session.userName,
                isAdmin: req.session.isAdmin || false
            } : null
        });
    }
}

module.exports = new AuthController();