const User = require('../models/userModel');
const RefreshToken = require('../models/refreshTokenModel');
const { generateAccessToken, generateRefreshToken } = require('../utils/jwtUtils');

const { OAuth2Client } = require('google-auth-library');
const googleClient = new OAuth2Client(
  process.env.GOOGLE_CLIENT_ID // This should be your WEB client ID
);

const authController = {
    register: async (req, res, next) => {
        try {
            const { email, first_name, last_name, role, contacts } = req.body;
            console.log(first_name)
            const  creator = req.userId;
            // Check if user exists
            const existingUser = await User.findByEmail(email);
            if (existingUser) {
                return res.status(400).json({ message: 'User already exists' });
            }
            // Create user
            const userId = await User.create(email, first_name, last_name,contacts, creator,  role);
            
            res.status(201).json({ 
                message: 'User registered successfully',
                userId 
            });
        } catch (error) {
            next(error);
        }
    },

    login: async (req, res, next) => {
        try {
            const { email, password } = req.body;
            
            // Find user
            const user = await User.findByEmail(email);
            if (!user) {
                return res.status(401).json({ message: 'Invalid credentials' });
            }
            
            // Check password
            const isMatch = await User.comparePasswords(password, user.password);
            if (!isMatch) {
                return res.status(401).json({ message: 'Invalid credentials' });
            }
            
            // Generate tokens
            const accessToken = generateAccessToken(user.id);
            const refreshToken = await generateRefreshToken(user.id, RefreshToken);
            
            res.json({
                accessToken,
                refreshToken,
                userId: user.id,
                role: user.role,
                name: user.first_name + " " + user.last_name,
                profilePicture: user.profile_url
            });

        } catch (error) {
            next(error);
        }
    },

    refreshToken: async (req, res, next) => {
        try {
            const { refreshToken } = req.body;
            
            if (!refreshToken) {
                return res.status(401).json({ message: 'Refresh token is required' });
            }
            
            // Verify refresh token
            const decoded = verifyToken(refreshToken);
            
            // Check if token exists in DB
            const tokenInDb = await RefreshToken.findByToken(refreshToken);
            if (!tokenInDb) {
                return res.status(403).json({ message: 'Invalid refresh token' });
            }
            
            // Generate new access token
            const newAccessToken = generateAccessToken(decoded.id);
            
            res.json({
                accessToken: newAccessToken
            });
        } catch (error) {
            next(error);
        }
    },

    logout: async (req, res, next) => {
        try {
            const { refreshToken } = req.body;
            
            if (!refreshToken) {
                return res.status(400).json({ message: 'Refresh token is required' });
            }
            
            // Delete the refresh token
            await RefreshToken.deleteByToken(refreshToken);
            
            res.json({ message: 'Logged out successfully' });
        } catch (error) {
            next(error);
        }
    },

googleTokenAuth: async (req, res, next) => {
    try {
        const { token } = req.body;
        
        if (!token) {
            return res.status(400).json({ 
                success: false,
                message: 'Google token is required' 
            });
        }
        
        // Verify the Google ID token
        const ticket = await googleClient.verifyIdToken({
            idToken: token,
            audience: [
                process.env.GOOGLE_CLIENT_ID, // Web client ID
                process.env.GOOGLE_ANDROID_CLIENT_ID // Android client ID
            ]
        });
        
        const payload = ticket.getPayload();
        
        if (!payload.email_verified) {
            return res.status(401).json({ 
                success: false,
                message: 'Google email not verified' 
            });
        }

        // Extract user information from payload
        const email = payload.email;

        // Check if user exists in database
        let user = await User.findByEmail(email);

        if (!user) {
            return res.status(404).json({ 
                success: false,
                message: 'User Not found' 
            });

        } 

        // Generate tokens
        const accessToken = generateAccessToken(user.id);
        const refreshToken = await generateRefreshToken(user.id, RefreshToken);
        
        // Return success response with user data
        return res.json({
            success: true,
            message: 'Google authentication successful',
            data: {
                accessToken,
                refreshToken,
                userId: user.id,
                role: user.role,
                name: `${user.first_name} ${user.last_name}`.trim(),
                email: user.email,
                profilePicture: user.profile_url
            }
        });

    } catch (error) {
        console.error('Google authentication error:', error);
        
        // Handle specific Google API errors
        if (error.message.includes('Token used too late')) {
            return res.status(401).json({ 
                success: false,
                message: 'Expired Google token' 
            });
        }
        
        if (error.message.includes('Invalid token signature')) {
            return res.status(401).json({ 
                success: false,
                message: 'Invalid Google token' 
            });
        }
        
        return res.status(500).json({ 
            success: false,
            message: 'Error authenticating with Google',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
}
};

module.exports = authController;