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

const abonemmentService = new AbonemmentService();

class CompanyRegisterController {
  static async register(req, res) {
    logger.info('CompanyRegisterController.register:start');
    try {
      console.log('🏢 Company registration attempt started');
      console.log('📋 Request body:', JSON.stringify(req.body, null, 2));
      
      const { 
        companyName,
        companyEmail,
        confirmCompanyEmail,
        companyPhone,
        contactPersonName,
        contactPersonPhone,
        password,
        confirmPassword
      } = req.body;
      
      console.log('🔍 Extracting company data:', {
        companyName,
        companyEmail,
        companyPhone,
        contactPersonName,
        contactPersonPhone
      });
      
      // Validate email match
      if (companyEmail !== confirmCompanyEmail) {
        logger.warn('CompanyRegisterController.register:email_mismatch', { companyEmail, confirmCompanyEmail });
        console.log('❌ Company email confirmation mismatch');
        return res.status(400).json({ 
          success: false, 
          message: 'Company email and confirm email do not match' 
        });
      }
      
      // Validate password match
      if (password !== confirmPassword) {
        logger.warn('CompanyRegisterController.register:password_mismatch');
        console.log('❌ Company password confirmation mismatch');
        return res.status(400).json({ 
          success: false, 
          message: 'Password and confirm password do not match' 
        });
      }
      
      // Check if company already exists
      console.log('🔍 Checking if company already exists:', companyEmail);
      const existingCompany = await CompanyUserService.findCompanyUserByEmail(companyEmail);
      if (existingCompany) {
        logger.warn('CompanyRegisterController.register:company_exists', { companyEmail });
        console.log('❌ Company registration failed: Company already exists');
        return res.status(400).json({ 
          success: false, 
          message: 'Company already exists' 
        });
      }
      
      // Create new company user
      console.log('📝 Creating new company user...');
      const newCompany = await CompanyUserService.createCompanyUser({
        companyEmail,
        companyName,
        companyPhone,
        contactPersonName,
        contactPersonPhone,
        password
      });

      await abonemmentService.linkGiftFlagsToUser(companyEmail, newCompany.id);
      
      logger.info('CompanyRegisterController.register:success', { companyId: newCompany.id });
      console.log('✅ Company user created successfully:', {
        companyId: newCompany.id,
        companyName: newCompany.companyName,
        companyEmail: newCompany.email,
        contactPerson: newCompany.contactPersonName
      });
      
      res.status(201).json({
        success: true,
        message: 'Company user registered successfully',
        companyId: newCompany.id
      });
      
    } catch (error) {
      logger.error('CompanyRegisterController.register:error', { error: error.message });
      console.error('💥 Company registration error:', error);
      res.status(500).json({
        success: false,
        message: 'Internal server error'
      });
    }
    logger.info('CompanyRegisterController.register:end');
  }
}

module.exports = CompanyRegisterController;