#!/usr/bin/env bash
set -euo pipefail

lines=${1:-20}
if [[ $# -gt 1 || ! $lines =~ ^[0-9]+$ ]]; then
    echo "Uso: $0 [cantidad_de_lineas]" >&2
    exit 2
fi

log_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/logs/dev"
host=webhookbc.consuerte.com.co
route=/webhook_whatsapp_pruebas
response="$(mktemp)"
trap 'rm -f -- "$response"' EXIT

systemctl is-active apache2
apache2ctl configtest
ss -H -ltn 'sport = :8086' | awk 'NF {print; found=1} END {exit !found}'

status=$(curl -sS --connect-timeout 5 --max-time 12 -o /dev/null -w '%{http_code}' \
    http://10.231.0.136:8094/webhook)
if [[ $status != 405 ]]; then
    echo "Backend de pruebas devolvió HTTP $status. Se esperaba 405 para GET." >&2
    exit 1
fi
echo "Backend de pruebas accesible. GET devolvió HTTP $status."

status=$(curl -sS --connect-timeout 5 --max-time 12 \
    --resolve "$host:8086:127.0.0.1" -o "$response" -w '%{http_code}' \
    -H 'Content-Type: application/json' --data '{}' \
    "https://$host:8086$route?token=control-invalido")
if [[ $status != 403 ]] || ! grep -q 'Token invalido' "$response"; then
    echo "El puente devolvió HTTP $status. Se esperaba el rechazo del token por Symfony." >&2
    exit 1
fi
echo "HTTPS y reenvío verificados. Symfony rechazó el token de prueba con HTTP 403."

log_file="$log_dir/$(date +%F)-access.log"
echo "Accesos recientes en $log_file"
tail -n "$lines" -- "$log_file" | sed -E 's/\?[^ "]*//g'
