#!/bin/bash

# Passwordless Authentication Test Runner
# Runs all tests for the passwordless authentication system

set -e

echo "=========================================="
echo "  Passwordless Authentication Tests"
echo "=========================================="
echo ""

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check prerequisites
echo -e "${BLUE}Checking prerequisites...${NC}"

# Check if app is running
if ! curl -s http://localhost:9000/en > /dev/null; then
    echo -e "${RED}❌ App is not running on port 9000${NC}"
    echo "Start the app with: npm run dev"
    exit 1
fi
echo -e "${GREEN}✅ App is running${NC}"

# Check if MailHog is running
if ! curl -s http://localhost:8025 > /dev/null; then
    echo -e "${RED}❌ MailHog is not running${NC}"
    echo "Start MailHog with: docker-compose --profile development up -d mailhog"
    exit 1
fi
echo -e "${GREEN}✅ MailHog is running${NC}"

# Check if Redis is running
if ! docker ps | grep -q mawidi-redis; then
    echo -e "${RED}❌ Redis is not running${NC}"
    echo "Start Redis with: docker-compose --profile development up -d redis"
    exit 1
fi
echo -e "${GREEN}✅ Redis is running${NC}"

# Check if PostgreSQL is running
if ! docker ps | grep -q mawidi-postgres; then
    echo -e "${RED}❌ PostgreSQL is not running${NC}"
    echo "Start PostgreSQL with: docker-compose --profile development up -d postgres"
    exit 1
fi
echo -e "${GREEN}✅ PostgreSQL is running${NC}"

echo ""
echo -e "${BLUE}All prerequisites met. Starting tests...${NC}"
echo ""

# Run unit tests
echo "=========================================="
echo "  1. Running Unit Tests"
echo "=========================================="
npm run test:unit -- __tests__/api/passwordless-auth.test.ts __tests__/integration/passwordless-flow.test.ts

echo ""
echo "=========================================="
echo "  2. Running E2E Tests - Passwordless Signup"
echo "=========================================="
npx playwright test tests/e2e/passwordless-signup.spec.ts --project=chromium

echo ""
echo "=========================================="
echo "  3. Running E2E Tests - Passwordless Login"
echo "=========================================="
npx playwright test tests/e2e/passwordless-login.spec.ts --project=chromium

echo ""
echo "=========================================="
echo "  Test Summary"
echo "=========================================="
echo ""
echo -e "${GREEN}✅ All passwordless authentication tests passed!${NC}"
echo ""
echo "Test Coverage:"
echo "- ✅ Passwordless signup (no password fields)"
echo "- ✅ Passwordless login (OTP by default)"
echo "- ✅ Duplicate email prevention"
echo "- ✅ Email personalization with names"
echo "- ✅ Professional email templates"
echo "- ✅ OTP verification"
echo "- ✅ Rate limiting"
echo "- ✅ Error handling"
echo "- ✅ Bilingual support (English/Arabic)"
echo ""
echo "View detailed report: npx playwright show-report"
echo ""
