const Joi = require('joi');

const validatePaymentMovil = (req, res, next) => {
  const schema = Joi.object({
    bank_code: Joi.string().length(4).required(),
    payer_identification: Joi.string().max(50).required(),
    payer_phone: Joi.string().max(20).required(),
    beneficiary_phone: Joi.string().max(20).required(),
    reference: Joi.string().max(100).required(),
    payment_date: Joi.date().required(),
    amount: Joi.number().positive().required(),
    bank_origin: Joi.string().length(4).required(),
    validate_identification: Joi.boolean().default(false)
  });

  const { error } = schema.validate(req.body);
  if (error) {
    return res.status(400).json({
      error: 'Datos de entrada inválidos',
      details: error.details
    });
  }

  next();
};

const validateConsultMovements = (req, res, next) => {
  const schema = Joi.object({
    bank_code: Joi.string().length(4).required(),
    account: Joi.string().max(50).required(),
    start_date: Joi.string().required(),
    end_date: Joi.string().required(),
    currency: Joi.string().default('VES'),
    movement_number: Joi.string().allow('')
  });

  const { error } = schema.validate(req.body);
  if (error) {
    return res.status(400).json({
      error: 'Datos de entrada inválidos',
      details: error.details
    });
  }

  next();
};

const validateBanco100Transaction = (req, res, next) => {
  const schema = Joi.object({
    bank_code: Joi.string().valid('0156').required(),
    transaction_type: Joi.string().valid('pago_movil', 'transferencia_cuenta', 'transferencia_telefono').required(),
    payer_identification: Joi.string().pattern(/^[VJE]\d+$/).required(),
    payer_account: Joi.string().max(20).required(),
    beneficiary_account: Joi.string().max(20).required(),
    beneficiary_identification: Joi.string().optional(),
    bank_destination: Joi.string().length(3).required(),
    reference: Joi.string().max(12).required(),
    payment_date: Joi.date().required(),
    amount: Joi.number().positive().precision(2).required()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    return res.status(400).json({
      error: 'Datos de entrada inválidos para 100% Banco',
      details: error.details
    });
  }

  next();
};

module.exports = {
  validatePaymentMovil,
  validateConsultMovements,
  validateBanco100Transaction
};