#!/bin/bash

# Sistema de Inventario Forestal - Test Runner
# Ejecuta todos los tipos de tests del sistema

echo "🌲 Sistema de Inventario Forestal - Guatemala"
echo "=============================================="
echo "Ejecutando suite completa de tests..."
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Test results
UNIT_TESTS_PASSED=0
PHP_TESTS_PASSED=0
INTEGRATION_TESTS_PASSED=0
E2E_TESTS_PASSED=0

echo -e "${BLUE}📋 1. Ejecutando Unit Tests (React)...${NC}"
echo "----------------------------------------"
if npm run test:unit -- --watchAll=false --coverage; then
    echo -e "${GREEN}✅ Unit Tests PASSED${NC}"
    UNIT_TESTS_PASSED=1
else
    echo -e "${RED}❌ Unit Tests FAILED${NC}"
fi
echo ""

echo -e "${BLUE}🐘 2. Ejecutando PHP Unit Tests...${NC}"
echo "-----------------------------------"
if composer install --dev && vendor/bin/phpunit; then
    echo -e "${GREEN}✅ PHP Tests PASSED${NC}"
    PHP_TESTS_PASSED=1
else
    echo -e "${RED}❌ PHP Tests FAILED${NC}"
fi
echo ""

echo -e "${BLUE}🔗 3. Ejecutando Integration Tests...${NC}"
echo "------------------------------------"
if npm test -- --testPathPattern=integration --watchAll=false; then
    echo -e "${GREEN}✅ Integration Tests PASSED${NC}"
    INTEGRATION_TESTS_PASSED=1
else
    echo -e "${RED}❌ Integration Tests FAILED${NC}"
fi
echo ""

echo -e "${BLUE}🎭 4. Ejecutando E2E Tests (Playwright)...${NC}"
echo "-------------------------------------------"
if npx playwright install && npm run test:e2e; then
    echo -e "${GREEN}✅ E2E Tests PASSED${NC}"
    E2E_TESTS_PASSED=1
else
    echo -e "${RED}❌ E2E Tests FAILED${NC}"
fi
echo ""

# Summary
echo "=============================================="
echo -e "${YELLOW}📊 RESUMEN DE TESTS${NC}"
echo "=============================================="

TOTAL_PASSED=$((UNIT_TESTS_PASSED + PHP_TESTS_PASSED + INTEGRATION_TESTS_PASSED + E2E_TESTS_PASSED))
TOTAL_TESTS=4

echo "Unit Tests (React):     $([ $UNIT_TESTS_PASSED -eq 1 ] && echo -e "${GREEN}PASSED${NC}" || echo -e "${RED}FAILED${NC}")"
echo "PHP Unit Tests:         $([ $PHP_TESTS_PASSED -eq 1 ] && echo -e "${GREEN}PASSED${NC}" || echo -e "${RED}FAILED${NC}")"
echo "Integration Tests:      $([ $INTEGRATION_TESTS_PASSED -eq 1 ] && echo -e "${GREEN}PASSED${NC}" || echo -e "${RED}FAILED${NC}")"
echo "E2E Tests:              $([ $E2E_TESTS_PASSED -eq 1 ] && echo -e "${GREEN}PASSED${NC}" || echo -e "${RED}FAILED${NC}")"
echo ""
echo "Total: $TOTAL_PASSED/$TOTAL_TESTS tests passed"

if [ $TOTAL_PASSED -eq $TOTAL_TESTS ]; then
    echo -e "${GREEN}🎉 ¡TODOS LOS TESTS PASARON!${NC}"
    echo "El sistema está listo para producción."
    exit 0
else
    echo -e "${RED}⚠️  ALGUNOS TESTS FALLARON${NC}"
    echo "Revisa los errores antes de desplegar."
    exit 1
fi