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

class PasswordRecoveryController {
    async requestPassword(req, res) {
        try {
            const { email } = req.body;
            
            if (!email) {
                return res.status(400).json({
                    success: false,
                    error: 'Email address is 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(`Password recovery requested for: ${email}`);
            
            // Find user in database
            const user = await nocodbService.getUserByEmail(email);
            
            if (!user) {
                // Don't reveal whether the email exists or not for security
                logger.warn(`Password recovery attempted for non-existent email: ${email}`);
                return res.json({
                    success: true,
                    message: 'If an account exists with this email, you will receive your password shortly.'
                });
            }
            
            // Send password email
            await sendPasswordRecovery(user);
            
            logger.info(`Password recovery email sent to: ${email}`);
            
            res.json({
                success: true,
                message: 'If an account exists with this email, you will receive your password shortly.'
            });
            
        } catch (error) {
            logger.error('Password recovery error:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to process password recovery request. Please try again later.'
            });
        }
    }
}

module.exports = new PasswordRecoveryController();
