const PersonalUserRepository = require('../../../repositories/user/personal/PersonalUserRepository');
const ReferralService = require('../../referral/ReferralService');
const UserStatusService = require('../../status/UserStatusService');
const UnitOfWork = require('../../../database/UnitOfWork');
const MailService = require('../../email/MailService');
const { logger } = require('../../../middleware/logger');

class PersonalUserService {
  static async createPersonalUser({ email, password, firstName, lastName, phone, referralEmail }) {
    logger.info('PersonalUserService.createPersonalUser:start', { email, firstName, lastName, hasReferral: !!referralEmail });
    console.log('📝 PersonalUserService: Creating personal user...');
    console.log('📋 Data to be saved:', { email, firstName, lastName, phone, hasReferral: !!referralEmail });

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

    // Register repositories
    unitOfWork.registerRepository('personalUser', new PersonalUserRepository(unitOfWork));

    try {
      // Create user and profile via repository
      const personalRepo = unitOfWork.getRepository('personalUser');
      const newUser = await personalRepo.create({
        email,
        password,
        firstName,
        lastName,
        phone,
        referralEmail
      });
      logger.info('PersonalUserService.createPersonalUser:user_created', { userId: newUser.id });

      // Initialize user status
      await UserStatusService.initializeUserStatus(newUser.id, 'personal', unitOfWork, 'pending');
      logger.info('PersonalUserService.createPersonalUser:user_status_initialized', { userId: newUser.id });

      // Handle referral if provided
      if (referralEmail) {
        logger.info('PersonalUserService.createPersonalUser:processing_referral', { userId: newUser.id, referralEmail });
        console.log('🔗 Processing referral email:', referralEmail);
        await ReferralService.processReferral(newUser.id, referralEmail, unitOfWork);
      }

      // Send registration email to the new user
      await MailService.sendRegistrationEmail({
        email: newUser.email,
        firstName: newUser.firstName,
        lastName: newUser.lastName,
        userType: 'personal'
      });
      logger.info('PersonalUserService.createPersonalUser:registration_email_sent', { email: newUser.email });

      await unitOfWork.commit();
      logger.info('PersonalUserService.createPersonalUser:success', { userId: newUser.id });
      return newUser;
    } catch (error) {
      logger.error('PersonalUserService.createPersonalUser:error', { email, error: error.message });
      await unitOfWork.rollback(error);
      console.error('💥 PersonalUserService: Error creating user:', error);
      throw error;
    }
  }

  static async findPersonalUserByEmail(email) {
    logger.info('PersonalUserService.findPersonalUserByEmail:start', { email });
    // For read-only, you can use a short-lived UnitOfWork or refactor as needed
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    unitOfWork.registerRepository('personalUser', new PersonalUserRepository(unitOfWork));
    try {
      const personalRepo = unitOfWork.getRepository('personalUser');
      const user = await personalRepo.findByEmail(email);
      await unitOfWork.commit();
      logger.info('PersonalUserService.findPersonalUserByEmail:success', { email, found: !!user });
      return user;
    } catch (error) {
      logger.error('PersonalUserService.findPersonalUserByEmail:error', { email, error: error.message });
      await unitOfWork.rollback(error);
      throw error;
    }
  }
}

module.exports = PersonalUserService;