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

class PaymentController {
  static async validatePaymentMovil(req, res, next) {
    try {
      console.log("📨 Recibiendo solicitud de validación:", {
        bank: req.body.bank_code,
        reference: req.body.reference,
        amount: req.body.amount,
      });

      const result = await BankService.processPayment(
        req.body.bank_code,
        req.body
      );

      console.log("✅ Validación completada:", {
        reference: req.body.reference,
        success: result.success,
        transactionId: result.transactionId,
        alreadyProcessed: result.alreadyProcessed || false,
      });

      const response = {
        success: result.success,
        data: result.data,
        transactionId: result.transactionId,
      };

      // Agregar información clara sobre el estado del pago
      if (result.alreadyProcessed) {
        response.alreadyProcessed = true;
        response.message = "⚠️ Este pago ya fue procesado anteriormente";
        response.status = "already_processed";
      } else {
        response.alreadyProcessed = false;
        response.status = result.success ? "new_processed" : "failed";
        response.message =
          result.message ||
          (result.success
            ? "✅ Pago procesado exitosamente"
            : "❌ Error procesando el pago");
      }

      if (result.isRetry) {
        response.isRetry = true;
        response.message =
          "🔄 Reintento de pago " + (result.success ? "exitoso" : "fallido");
      }

      res.json(response);
    } catch (error) {
      console.error("❌ Error en validatePaymentMovil:", error.message);
      next(error);
    }
  }

  static async consultMovements(req, res, next) {
    try {
      const result = await BankService.consultMovements(
        req.body.bank_code,
        req.body
      );

      res.json({
        success: result.success,
        data: result.data,
      });
    } catch (error) {
      next(error);
    }
  }

  static async getTransactionStatus(req, res, next) {
    try {
      const { reference } = req.params;
      const transaction = await Transaction.findByReference(reference);

      if (!transaction) {
        return res.status(404).json({
          error: "Transacción no encontrada",
        });
      }

      res.json({
        reference: transaction.reference,
        status: transaction.status,
        amount: transaction.amount,
        bank_response: {
          code: transaction.bank_response_code,
          message: transaction.bank_response_message,
        },
        created_at: transaction.created_at,
      });
    } catch (error) {
      next(error);
    }
  }

  static async validateTransaction100(req, res, next) {
    try {
      const result = await BankService.validateTransaction100(
        req.body.bank_code,
        req.body
      );

      res.json({
        success: result.success,
        data: result.data,
        transactionId: result.transactionId,
        message: result.success
          ? "Transacción validada exitosamente"
          : "Error en validación",
      });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = PaymentController;
