const CompanyUserRepository = require('../../../repositories/user/company/CompanyUserRepository');
const { logger } = require('../../../middleware/logger');

class CompanyProfileService {
  static async completeProfile(userId, profileData, unitOfWork) {
    logger.info('CompanyProfileService.completeProfile:start', { userId });
    try {
      const conn = unitOfWork.connection;

      const required = [
        { key: 'companyName', label: 'Company name' },
        { key: 'address', label: 'Street & number' },
        { key: 'zip_code', label: 'Postal code' },
        { key: 'city', label: 'City' },
        { key: 'country', label: 'Country' },
        { key: 'accountHolderName', label: 'Account holder' },
        { key: 'iban', label: 'IBAN' }
      ];

      for (const field of required) {
        const value = (profileData[field.key] || '').toString().trim();
        if (!value) {
          throw new Error(`${field.label} is required.`);
        }
      }

      profileData.companyName = (profileData.companyName || '').toString().trim();
  profileData.registrationNumber = (profileData.registrationNumber || '').toString().trim() || null;
  profileData.atuNumber = (profileData.atuNumber || profileData.uidNumber || '').toString().trim() || null;

      // Pass all profileData including country to repository
      const repo = new CompanyUserRepository(unitOfWork);
      await repo.updateProfileAndMarkCompleted(userId, profileData);
      logger.info('CompanyProfileService.completeProfile:profile_completed', { userId });

      // Check if all steps are complete and set status to 'pending' if so
      const UserStatusService = require('../../status/UserStatusService');
      await UserStatusService.checkAndSetPendingIfComplete(userId, unitOfWork);
      logger.info('CompanyProfileService.completeProfile:pending_check_complete', { userId });
      logger.info('CompanyProfileService.completeProfile:success', { userId });
      return true;
    } catch (error) {
      logger.error('CompanyProfileService.completeProfile:error', { userId, error: error.message });
      throw error;
    }
  }
}

module.exports = CompanyProfileService;
