const UserDocumentRepository = require('../../../repositories/documents/UserDocumentRepository');
const { uploadBuffer } = require('../../../utils/exoscaleUploader');
const { logger } = require('../../../middleware/logger');

class CompanyDocumentService {
  static async uploadCompanyId({ userId, idType, idNumber, expiryDate, files, unitOfWork }) {
    logger.info('CompanyDocumentService.uploadCompanyId:start', { userId, idType, idNumber, expiryDate });
    try {
      if (!idType || !expiryDate || !files || !files.front) {
        logger.warn('CompanyDocumentService.uploadCompanyId:missing_fields', { userId });
        throw new Error('Missing required fields or front image');
      }

      const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
      if (!allowedTypes.includes(files.front.mimetype)) {
        logger.warn('CompanyDocumentService.uploadCompanyId:invalid_front_type', { userId, mimetype: files.front.mimetype });
        throw new Error('Invalid file type for front image');
      }
      if (files.back && !allowedTypes.includes(files.back.mimetype)) {
        logger.warn('CompanyDocumentService.uploadCompanyId:invalid_back_type', { userId, mimetype: files.back.mimetype });
        throw new Error('Invalid file type for back image');
      }

      logger.info('CompanyDocumentService.uploadCompanyId:uploading_front', { userId });
      const frontUpload = await uploadBuffer(
        files.front.buffer,
        files.front.originalname,
        files.front.mimetype,
        `company-id/${userId}`
      );

      let backUpload = null;
      if (files.back) {
        logger.info('CompanyDocumentService.uploadCompanyId:uploading_back', { userId });
        backUpload = await uploadBuffer(
          files.back.buffer,
          files.back.originalname,
          files.back.mimetype,
          `company-id/${userId}`
        );
      }

      const repo = new UserDocumentRepository(unitOfWork);

      await repo.insertIdDocument({
        userId,
        documentType: 'company_id',
        frontObjectStorageId: frontUpload.objectKey,
        backObjectStorageId: backUpload ? backUpload.objectKey : null,
        idType,
        idNumber,
        expiryDate,
        originalFilenameFront: files.front.originalname,
        originalFilenameBack: files.back ? files.back.originalname : null
      });
      logger.info('CompanyDocumentService.uploadCompanyId:id_document_inserted', { userId });

      await unitOfWork.connection.query(
        `UPDATE user_status SET documents_uploaded = 1, documents_uploaded_at = NOW() WHERE user_id = ?`,
        [userId]
      );
      logger.info('CompanyDocumentService.uploadCompanyId:user_status_updated', { userId });

      const UserStatusService = require('../../status/UserStatusService');
      await UserStatusService.checkAndSetPendingIfComplete(userId, unitOfWork);
      logger.info('CompanyDocumentService.uploadCompanyId:pending_check_complete', { userId });

      logger.info('CompanyDocumentService.uploadCompanyId:success', { userId });
      return {
        front: frontUpload,
        back: backUpload
      };
    } catch (error) {
      logger.error('CompanyDocumentService.uploadCompanyId:error', { userId, error: error.message });
      throw error;
    }
  }
}

module.exports = CompanyDocumentService;