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

class UserStatusService {
  static async initializeUserStatus(userId, userType, unitOfWork, status = 'pending') {
    logger.info('UserStatusService.initializeUserStatus:start', { userId, userType, status });
    try {
      const repo = new UserStatusRepository(unitOfWork);
      await repo.initializeUserStatus(userId, status);
      logger.info('UserStatusService.initializeUserStatus:success', { userId });
    } catch (error) {
      logger.error('UserStatusService.initializeUserStatus:error', { userId, error: error.message });
      throw error;
    }
  }

  static async updateEmailVerified(userId, unitOfWork) {
    logger.info('UserStatusService.updateEmailVerified:start', { userId });
    try {
      const repo = new UserStatusRepository(unitOfWork);
      await repo.updateEmailVerified(userId);
      logger.info('UserStatusService.updateEmailVerified:success', { userId });
    } catch (error) {
      logger.error('UserStatusService.updateEmailVerified:error', { userId, error: error.message });
      throw error;
    }
  }

  static async markRegistrationComplete(userId, unitOfWork) {
    logger.info('UserStatusService.markRegistrationComplete:start', { userId });
    try {
      const repo = new UserStatusRepository(unitOfWork);
      await repo.markRegistrationComplete(userId);
      logger.info('UserStatusService.markRegistrationComplete:success', { userId });
    } catch (error) {
      logger.error('UserStatusService.markRegistrationComplete:error', { userId, error: error.message });
      throw error;
    }
  }

  static async checkAndSetPendingIfComplete(userId, unitOfWork) {
    logger.info('UserStatusService.checkAndSetPendingIfComplete:start', { userId });
    try {
      const repo = new UserStatusRepository(unitOfWork);
      // Only set to 'pending' if all quickactions are complete and status is 'inactive'
      await repo.setPendingIfComplete(userId);
      logger.info('UserStatusService.checkAndSetPendingIfComplete:success', { userId });
    } catch (error) {
      logger.error('UserStatusService.checkAndSetPendingIfComplete:error', { userId, error: error.message });
      throw error;
    }
  }

  static async getStatusProgress(userId, unitOfWork) {
    logger.info('UserStatusService.getStatusProgress:start', { userId });
    try {
      const repo = new UserStatusRepository(unitOfWork);
      const status = await repo.getStatusByUserId(userId);
      if (!status) return null;

      // Guest users: check if email verification is still needed
      if (status.status === 'active') {
        const conn = unitOfWork.connection;
        const [userRows] = await conn.query('SELECT role FROM users WHERE id = ? LIMIT 1', [userId]);
        if (userRows?.[0]?.role === 'guest') {
          // For guests, only email_verified matters — other steps are auto-completed
          const emailVerified = !!status.email_verified;
          const guestSteps = [
            { key: 'email_verified', label: 'Email Verified', completed: emailVerified },
            { key: 'profile_completed', label: 'Profile Completed', completed: true },
            { key: 'documents_uploaded', label: 'Documents Uploaded', completed: true },
            { key: 'contract_signed', label: 'Contract Signed', completed: true },
          ];
          const completedCount = guestSteps.filter(s => s.completed).length;
          return {
            status: 'active',
            isGuest: true,
            steps: guestSteps,
            completedSteps: guestSteps.filter(s => s.completed).map(s => s.label),
            progressPercent: Math.round((completedCount / guestSteps.length) * 100),
          };
        }
      }

      // Calculate progress steps
      const steps = [
        { key: 'email_verified', label: 'Email Verified' },
        { key: 'profile_completed', label: 'Profile Completed' },
        { key: 'documents_uploaded', label: 'Documents Uploaded' },
        { key: 'contract_signed', label: 'Contract Signed' }
      ];
      const completedSteps = steps.filter(s => !!status[s.key]);
      const progressPercent = Math.round((completedSteps.length / steps.length) * 100);

      return {
        status: status.status,
        steps: steps.map(s => ({
          key: s.key,
          label: s.label,
          completed: !!status[s.key]
        })),
        completedSteps: completedSteps.map(s => s.label),
        progressPercent
      };
    } catch (error) {
      logger.error('UserStatusService.getStatusProgress:error', { userId, error: error.message });
      throw error;
    }
  }
}

module.exports = UserStatusService;
