const CompanyUserRepository = require('../../../repositories/user/company/CompanyUserRepository');
const UserStatusService = require('../../status/UserStatusService');
const UnitOfWork = require('../../../database/UnitOfWork');
const CompanyUser = require('../../../models/CompanyUser');
const MailService = require('../../email/MailService');
const { logger } = require('../../../middleware/logger');

class CompanyUserService {
  static async createCompanyUser({ companyEmail, password, companyName, companyPhone, contactPersonName, contactPersonPhone }) {
    logger.info('CompanyUserService.createCompanyUser:start', { companyEmail, companyName });
    console.log('📝 CompanyUserService: Creating company user...');
    console.log('📋 Data to be saved:', { companyEmail, companyName, companyPhone, contactPersonName });

    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();

    // Register repositories
    unitOfWork.registerRepository('companyUser', new CompanyUserRepository(unitOfWork));

    try {
      const companyRepo = unitOfWork.getRepository('companyUser');
      const newCompany = await companyRepo.create({
        companyEmail,
        password,
        companyName,
        companyPhone,
        contactPersonName,
        contactPersonPhone
      });

      logger.info('CompanyUserService.createCompanyUser:company_created', { companyId: newCompany.id });

      // Initialize user status
      await UserStatusService.initializeUserStatus(newCompany.id, 'company', unitOfWork, 'pending');
      logger.info('CompanyUserService.createCompanyUser:user_status_initialized', { companyId: newCompany.id });

      // Send registration email to the new company user
      await MailService.sendRegistrationEmail({
        email: newCompany.email,
        userType: 'company',
        companyName: newCompany.companyName
      });
      logger.info('CompanyUserService.createCompanyUser:registration_email_sent', { companyEmail });

      await unitOfWork.commit();
      logger.info('CompanyUserService.createCompanyUser:success', { companyId: newCompany.id });
      return newCompany;
    } catch (error) {
      logger.error('CompanyUserService.createCompanyUser:error', { companyEmail, error: error.message });
      await unitOfWork.rollback(error);
      console.error('💥 CompanyUserService: Error creating company user:', error);
      throw error;
    }
  }

  static async findCompanyUserByEmail(email) {
    logger.info('CompanyUserService.findCompanyUserByEmail:start', { email });
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    unitOfWork.registerRepository('companyUser', new CompanyUserRepository(unitOfWork));
    try {
      const companyRepo = unitOfWork.getRepository('companyUser');
      const user = await companyRepo.findByEmail(email);
      await unitOfWork.commit();
      logger.info('CompanyUserService.findCompanyUserByEmail:success', { email, found: !!user });
      return user;
    } catch (error) {
      logger.error('CompanyUserService.findCompanyUserByEmail:error', { email, error: error.message });
      await unitOfWork.rollback(error);
      throw error;
    }
  }
}

module.exports = CompanyUserService;