const UnitOfWork = require('../../database/UnitOfWork');
const UserStatusRepository = require('../../repositories/status/UserStatusRepository');
const UserStatusService = require('../../services/status/UserStatusService');
const { logger } = require('../../middleware/logger');

class UserStatusController {
  static async getStatus(req, res) {
    const userId = req.user.userId;
    logger.info(`[UserStatusController] getStatus called for userId: ${userId}`);
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    unitOfWork.registerRepository('userStatus', new UserStatusRepository(unitOfWork));
    try {
      const userStatusRepo = unitOfWork.getRepository('userStatus');
      let status = await userStatusRepo.getStatusByUserId(userId);
      
      // If no status exists, create one with default values
      if (!status) {
        logger.info(`[UserStatusController] No status found for userId: ${userId}, creating default status`);
        await userStatusRepo.initializeUserStatus(userId, 'pending');
        status = await userStatusRepo.getStatusByUserId(userId);
      }
      
      await unitOfWork.commit();
      
      if (!status) {
        logger.warn(`[UserStatusController] Failed to create status for userId: ${userId}`);
        return res.status(500).json({ success: false, message: 'Failed to initialize user status' });
      }
      
      logger.info(`[UserStatusController] getStatus success for userId: ${userId}`, { status });
      return res.json({ success: true, status });
    } catch (error) {
      logger.error(`[UserStatusController] getStatus error for userId: ${userId}`, { error });
      await unitOfWork.rollback(error);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  }

  static async getStatusProgress(req, res) {
    const userId = req.user.userId;
    logger.info(`[UserStatusController] getStatusProgress called for userId: ${userId}`);
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    unitOfWork.registerRepository('userStatus', new UserStatusRepository(unitOfWork));
    try {
      // Use service to get progress details
      const progress = await UserStatusService.getStatusProgress(userId, unitOfWork);
      await unitOfWork.commit();
      if (!progress) {
        logger.warn(`[UserStatusController] No status found for userId: ${userId}`);
        return res.status(404).json({ success: false, message: 'User status not found' });
      }
      logger.info(`[UserStatusController] getStatusProgress success for userId: ${userId}`);
      return res.json({ success: true, progress });
    } catch (error) {
      logger.error(`[UserStatusController] getStatusProgress error for userId: ${userId}`, { error });
      await unitOfWork.rollback(error);
      return res.status(500).json({ success: false, message: 'Internal server error' });
    }
  }
}

module.exports = UserStatusController;
