#!/bin/bash

export E2E_ADMIN_USER=mb
export E2E_ADMIN_PASSWORD="monse$(date +%H)"

# ── Colores ─────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'

run_all() {
  npx playwright test
}

run_spec() {
  SPEC="$1"
  REPORTER="${2:-list}"

  if [ ! -f "$SPEC" ]; then
    echo -e "${RED}No existe el test: $SPEC${RESET}"
    exit 1
  fi

  npx playwright test "$SPEC" --reporter="$REPORTER"
}

run_grep() {
  PATTERN="$1"

  if [ -z "$PATTERN" ]; then
    echo "Patrón vacío."
    exit 1
  fi

  npx playwright test --grep "$PATTERN" --reporter=list
}

find_specs() {
  QUERY="$1"
  find tests -type f -name "*.spec.ts" | grep -i "$QUERY"
}

# ── Opción 6: Correr archivos uno por uno ───────────────────────────────────
run_one_by_one() {
  SPECS=($(find tests -type f -name "*.spec.ts" | sort))
  TOTAL=${#SPECS[@]}

  if [ "$TOTAL" -eq 0 ]; then
    echo -e "${RED}No se encontraron archivos .spec.ts en tests/${RESET}"
    exit 1
  fi

  echo ""
  echo -e "${BOLD}Corriendo $TOTAL archivos de tests uno por uno...${RESET}"
  echo -e "Usuario: ${CYAN}$E2E_ADMIN_USER${RESET}  |  Password: ${CYAN}$E2E_ADMIN_PASSWORD${RESET}"
  echo ""

  PASS_LIST=()
  FAIL_LIST=()
  SKIP_LIST=()
  COUNTER=0

  for SPEC in "${SPECS[@]}"; do
    COUNTER=$((COUNTER + 1))
    BASENAME=$(basename "$SPEC")
    echo -e "${BOLD}[$COUNTER/$TOTAL]${RESET} ${CYAN}$BASENAME${RESET}"
    echo "────────────────────────────────────────────────────────"

    # Correr con reporter=list para salida legible en consola
    OUTPUT=$(npx playwright test "$SPEC" --reporter=list 2>&1)
    EXIT_CODE=$?

    echo "$OUTPUT"

    # Determinar resultado
    if echo "$OUTPUT" | grep -q "0 passed" && echo "$OUTPUT" | grep -q "skipped"; then
      SKIP_LIST+=("$BASENAME")
      echo -e "${YELLOW}  → SKIPPED${RESET}"
    elif [ $EXIT_CODE -eq 0 ]; then
      PASS_LIST+=("$BASENAME")
      echo -e "${GREEN}  → PASS${RESET}"
    else
      FAIL_LIST+=("$BASENAME")
      echo -e "${RED}  → FAIL${RESET}"
    fi

    echo ""
  done

  # ── Resumen ────────────────────────────────────────────────────────────────
  echo ""
  echo "════════════════════════════════════════════════════════"
  echo -e "${BOLD}RESUMEN FINAL${RESET}"
  echo "════════════════════════════════════════════════════════"
  echo -e "${GREEN}PASS  (${#PASS_LIST[@]}):${RESET}"
  for F in "${PASS_LIST[@]}"; do echo "  ✓  $F"; done

  if [ ${#FAIL_LIST[@]} -gt 0 ]; then
    echo ""
    echo -e "${RED}FAIL  (${#FAIL_LIST[@]}):${RESET}"
    for F in "${FAIL_LIST[@]}"; do echo "  ✗  $F"; done
  fi

  if [ ${#SKIP_LIST[@]} -gt 0 ]; then
    echo ""
    echo -e "${YELLOW}SKIP  (${#SKIP_LIST[@]}):${RESET}"
    for F in "${SKIP_LIST[@]}"; do echo "  -  $F"; done
  fi

  echo "────────────────────────────────────────────────────────"
  echo "Total: $TOTAL  |  Pass: ${#PASS_LIST[@]}  |  Fail: ${#FAIL_LIST[@]}  |  Skip: ${#SKIP_LIST[@]}"

  if [ ${#FAIL_LIST[@]} -gt 0 ]; then
    echo ""
    echo -e "${YELLOW}TIP: Para ver detalles de un archivo fallido:${RESET}"
    echo "  bash test-e2e.sh  →  opción 2 → ruta del .spec.ts"
    echo ""
    echo -e "${YELLOW}Para ver solo los tests que fallaron con detalle:${RESET}"
    echo "  npx playwright test <archivo.spec.ts> --reporter=list"
    echo ""
    echo -e "${YELLOW}Para abrir el reporte HTML completo:${RESET}"
    echo "  npx playwright show-report"
    exit 1
  fi
}

# ── Menú ─────────────────────────────────────────────────────────────────────
echo "════════════════════════════════════════════"
echo -e "${BOLD}Tests E2E Playwright${RESET}"
echo "Usuario: $E2E_ADMIN_USER  |  Pass: $E2E_ADMIN_PASSWORD"
echo "════════════════════════════════════════════"
echo "1) Todos los tests (reporte HTML)"
echo "2) Un archivo .spec.ts (reporte consola)"
echo "3) Tests por nombre/patrón (--grep)"
echo "4) Sugerir test desde plantilla Twig"
echo "5) Solo si hay Twig modificados"
echo "6) Correr archivos uno por uno (debug)"
echo "════════════════════════════════════════════"

read -p "Opción [1-6]: " OPTION

case "$OPTION" in
  1)
    run_all
    ;;

  2)
    echo ""
    echo "Tests disponibles:"
    find tests -type f -name "*.spec.ts"
    echo ""

    read -p "Ruta del .spec.ts: " SPEC
    run_spec "$SPEC" "list"
    ;;

  3)
    read -p "Texto del test, describe o título: " PATTERN
    run_grep "$PATTERN"
    ;;

  4)
    read -p "Ruta de la plantilla .twig: " TWIG

    if [ ! -f "$TWIG" ]; then
      echo "No existe la plantilla: $TWIG"
      exit 1
    fi

    DIRNAME=$(basename "$(dirname "$TWIG")")
    BASENAME=$(basename "$TWIG" .html.twig)

    echo ""
    echo "Buscando specs relacionados con: $DIRNAME / $BASENAME"
    echo ""

    MATCHES=$(find_specs "$DIRNAME")
    if [ -z "$MATCHES" ]; then
      MATCHES=$(find_specs "$BASENAME")
    fi

    if [ -z "$MATCHES" ]; then
      echo "No encontré .spec.ts relacionado automáticamente."
      echo ""
      echo "Specs disponibles:"
      find tests -type f -name "*.spec.ts"
      echo ""
      read -p "Ingresá la ruta del .spec.ts a ejecutar: " SPEC
      run_spec "$SPEC" "list"
    else
      echo "Specs encontrados:"
      echo "$MATCHES"
      echo ""

      COUNT=$(echo "$MATCHES" | wc -l | tr -d ' ')

      if [ "$COUNT" = "1" ]; then
        SPEC="$MATCHES"
        echo "Ejecutando: $SPEC"
        run_spec "$SPEC" "list"
      else
        echo "Hay varios posibles."
        read -p "Copiá la ruta exacta del .spec.ts a ejecutar: " SPEC
        run_spec "$SPEC" "list"
      fi
    fi
    ;;

  5)
    CHANGED_TWIG=$(git diff --name-only HEAD | grep '\.twig$')

    if [ -z "$CHANGED_TWIG" ]; then
      echo "No hay plantillas Twig modificadas."
      exit 0
    fi

    echo ""
    echo "Plantillas Twig modificadas:"
    echo "$CHANGED_TWIG"
    echo ""

    echo "Specs disponibles:"
    find tests -type f -name "*.spec.ts"
    echo ""

    read -p "Ingresá .spec.ts a ejecutar o texto para --grep: " TARGET

    if [ -f "$TARGET" ]; then
      run_spec "$TARGET" "list"
    else
      run_grep "$TARGET"
    fi
    ;;

  6)
    run_one_by_one
    ;;

  *)
    echo "Opción inválida."
    exit 1
    ;;
esac
