const UnitOfWork = require('../../database/UnitOfWork');
const EmailVerificationRepository = require('../../repositories/email/EmailVerificationRepository');
const EmailVerificationService = require('../../services/email/EmailVerificationService');
const { logger } = require('../../middleware/logger');

class EmailVerificationController {
  static async sendVerificationEmail(req, res) {
    const userId = req.user.userId;
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const emailVerificationRepo = new EmailVerificationRepository(unitOfWork);
      const userRecord = await emailVerificationRepo.getUserBasic(userId);
      if (!userRecord) {
        await unitOfWork.rollback();
        logger.warn(`User not found for email verification: ${userId}`);
        return res.status(404).json({ success: false, message: 'User not found' });
      }
      await EmailVerificationService.sendVerificationEmail(userRecord, unitOfWork);
      await unitOfWork.commit();
      logger.info(`Verification email sent to user ${userId}`);
      res.json({ success: true, message: 'Verification email sent' });
    } catch (error) {
      await unitOfWork.rollback(error);
      logger.error('Error sending verification email', { message: error?.message, stack: error?.stack });
      res.status(400).json({ success: false, message: error.message });
    }
  }

  static async verifyEmailCode(req, res) {
    const userId = req.user.userId;
    const { code } = req.body;
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const result = await EmailVerificationService.verifyCode(userId, code, unitOfWork);
      await unitOfWork.commit();
      if (result.success) {
        logger.info(`Email verified for user ${userId}`);
        return res.json({ success: true });
      } else {
        logger.warn(`Failed email verification for user ${userId}: ${result.error}`);
        return res.status(400).json({ success: false, error: result.error });
      }
    } catch (error) {
      await unitOfWork.rollback(error);
      logger.error('Error verifying email code', { message: error?.message, stack: error?.stack });
      res.status(400).json({ success: false, error: error.message });
    }
  }
}

module.exports = EmailVerificationController;
