const UnitOfWork = require('../../database/UnitOfWork');
const CompanyDocumentService = require('../../services/documents/company/CompanyDocumentService');
const { logger } = require('../../middleware/logger');

class CompanyDocumentController {
  static async uploadCompanyId(req, res) {
    const userId = req.user.userId;
    logger.info(`[CompanyDocumentController] uploadCompanyId called for userId: ${userId}`);
    const { idType, idNumber, expiryDate } = req.body;
    const files = {
      front: req.files['front'] ? req.files['front'][0] : null,
      back: req.files['back'] ? req.files['back'][0] : null
    };
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const result = await CompanyDocumentService.uploadCompanyId({
        userId,
        idType,
        idNumber,
        expiryDate,
        files,
        unitOfWork
      });
      await unitOfWork.commit();
      logger.info(`[CompanyDocumentController] uploadCompanyId success for userId: ${userId}`);
      res.json({ success: true, uploads: result });
    } catch (error) {
      logger.error(`[CompanyDocumentController] uploadCompanyId error for userId: ${userId}`, { error });
      await unitOfWork.rollback(error);
      res.status(400).json({ success: false, message: error.message });
    }
  }
}

module.exports = CompanyDocumentController;
