const PersonalUserService = require('../../services/user/personal/PersonalUserService');
const AbonemmentService = require('../../services/abonemments/AbonemmentService');
const { logger } = require('../../middleware/logger'); // add logger import

const abonemmentService = new AbonemmentService();

class PersonalRegisterController {
  static async register(req, res) {
    logger.info('PersonalRegisterController.register:start');
    try {
      console.log('📝 Personal registration attempt started');
      console.log('📋 Request body:', JSON.stringify(req.body, null, 2));
      
      const { 
        firstName, 
        lastName, 
        email, 
        confirmEmail, 
        phone, 
        password, 
        confirmPassword, 
        referralEmail 
      } = req.body;
      
      console.log('🔍 Extracting user data:', {
        firstName,
        lastName,
        email,
        phone,
        hasReferral: !!referralEmail
      });
      
      // Validate email match
      if (email !== confirmEmail) {
        logger.warn('PersonalRegisterController.register:email_mismatch', { email, confirmEmail });
        console.log('❌ Email confirmation mismatch');
        return res.status(400).json({ 
          success: false, 
          message: 'Email and confirm email do not match' 
        });
      }
      
      // Validate password match
      if (password !== confirmPassword) {
        logger.warn('PersonalRegisterController.register:password_mismatch');
        console.log('❌ Password confirmation mismatch');
        return res.status(400).json({ 
          success: false, 
          message: 'Password and confirm password do not match' 
        });
      }
      
      // Check if user already exists
      console.log('🔍 Checking if user already exists:', email);
      const existingUser = await PersonalUserService.findPersonalUserByEmail(email);
      if (existingUser) {
        logger.warn('PersonalRegisterController.register:user_exists', { email });
        console.log('❌ Personal registration failed: User already exists');
        return res.status(400).json({ 
          success: false, 
          message: 'User already exists' 
        });
      }
      
      // Create new personal user
      console.log('📝 Creating new personal user...');
      const newUser = await PersonalUserService.createPersonalUser({
        firstName,
        lastName,
        email,
        phone,
        password,
        referralEmail
      });

      await abonemmentService.linkGiftFlagsToUser(email, newUser.id);
      
      logger.info('PersonalRegisterController.register:success', { userId: newUser.id });
      console.log('✅ Personal user created successfully:', {
        userId: newUser.id,
        email: newUser.email,
        firstName: newUser.firstName,
        lastName: newUser.lastName
      });
      
      res.status(201).json({
        success: true,
        message: 'Personal user registered successfully',
        userId: newUser.id
      });
      
    } catch (error) {
      logger.error('PersonalRegisterController.register:error', { error: error.message });
      console.error('💥 Personal registration error:', error);
      res.status(500).json({
        success: false,
        message: 'Internal server error'
      });
    }
    logger.info('PersonalRegisterController.register:end');
  }
}

module.exports = PersonalRegisterController;
