const BankService = require('../services/bankService');
const Transaction = require('../models/Transaction');

class RetryController {
  static async retryPayment(req, res, next) {
    try {
      const { transaction_id } = req.body;

      if (!transaction_id) {
        return res.status(400).json({
          error: 'Se requiere transaction_id'
        });
      }

      const result = await BankService.retryPayment(transaction_id);

      res.json({
        success: result.success,
        data: result.data,
        transactionId: result.transactionId,
        isRetry: true,
        retryCount: result.retryCount,
        message: result.success ? 'Reintento exitoso' : 'Reintento fallido'
      });

    } catch (error) {
      console.error('❌ Error en retryPayment:', error.message);
      next(error);
    }
  }

  static async getFailedTransactions(req, res, next) {
    try {
      const { bank_code, hours = 24 } = req.query;
      
      const bank = await Bank.findByCode(bank_code);
      if (!bank) {
        return res.status(400).json({ error: 'Banco no válido' });
      }

      // Esta función necesitarías crearla en el modelo
      const failedTransactions = await Transaction.findRecentFailedTransactions(
        bank.id, 
        parseInt(hours)
      );

      res.json({
        count: failedTransactions.length,
        transactions: failedTransactions.map(tx => ({
          id: tx.id,
          reference: tx.reference,
          amount: tx.amount,
          created_at: tx.created_at,
          retry_count: tx.retry_count,
          last_retry_at: tx.last_retry_at,
          bank_response_message: tx.bank_response_message
        }))
      });

    } catch (error) {
      console.error('❌ Error en getFailedTransactions:', error.message);
      next(error);
    }
  }
}

module.exports = RetryController;