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

class PersonalDocumentController {
  static async uploadPersonalId(req, res) {
    const userId = req.user.userId;
    logger.info(`[PersonalDocumentController] uploadPersonalId 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 PersonalDocumentService.uploadPersonalId({
        userId,
        idType,
        idNumber,
        expiryDate,
        files,
        unitOfWork
      });
      await unitOfWork.commit();
      logger.info(`[PersonalDocumentController] uploadPersonalId success for userId: ${userId}`);
      res.json({ success: true, uploads: result });
    } catch (error) {
      logger.error(`[PersonalDocumentController] uploadPersonalId error for userId: ${userId}`, { error });
      await unitOfWork.rollback(error);
      res.status(400).json({ success: false, message: error.message });
    }
  }
}

module.exports = PersonalDocumentController;
