class Helpers {
  formatCurrency(amount, currency = "VES") {
    return new Intl.NumberFormat("es-VE", {
      style: "currency",
      currency: currency,
      minimumFractionDigits: 2,
    }).format(amount);
  }

  formatDate(date, includeTime = true) {
    const options = {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    };

    if (includeTime) {
      options.hour = "2-digit";
      options.minute = "2-digit";
      options.second = "2-digit";
    }

    return new Date(date).toLocaleDateString("es-VE", options);
  }

  delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  async retryOperation(operation, maxRetries = 3, delayMs = 1000) {
    let lastError;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        lastError = error;
        console.warn(`Intento ${attempt} fallido:`, error.message);

        if (attempt < maxRetries) {
          await this.delay(delayMs * attempt); // Backoff exponencial
        }
      }
    }

    throw lastError;
  }

  validatePhoneNumber(phone) {
    const phoneRegex = /^04[12|14|16|24|26]\d{7}$/;
    return phoneRegex.test(phone);
  }

  validateDocumentNumber(doc) {
    if (!doc) return false;

    // Validar cédula venezolana (V12345678) o RIF (J123456789)
    const docRegex = /^[VEJPGvejpg]\d{5,9}$/;
    return docRegex.test(doc.toUpperCase());
  }

  sanitizeAmount(amount) {
    // Convertir string con comas a número
    if (typeof amount === "string") {
      return parseFloat(amount.replace(/\./g, "").replace(",", "."));
    }
    return amount;
  }

  generateReference(prefix = "REF") {
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).substring(2, 8);
    return `${prefix}-${timestamp}-${random}`.toUpperCase();
  }
}

module.exports = new Helpers();
