#!/bin/bash

###############################################################################
# User Management Feature Test Runner
#
# Runs all tests for the user management feature in the correct order
# Usage: ./scripts/test-user-management.sh [options]
#
# Options:
#   --unit-only       Run only unit tests
#   --e2e-only        Run only E2E tests
#   --quick           Run quick smoke tests
#   --full            Run complete test suite (default)
#   --coverage        Generate coverage report
###############################################################################

set -e  # Exit on error

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

# Test mode
MODE="${1:---full}"

echo -e "${BLUE}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║  User Management Feature - Test Suite Runner            ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""

# Check if database is running
echo -e "${YELLOW}[1/7]${NC} Checking database connection..."
if npx prisma db pull --schema=prisma/schema.prisma > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Database connection OK"
else
    echo -e "${RED}✗${NC} Database not accessible. Start with: docker-compose up -d postgres"
    exit 1
fi

# Ensure Prisma client is generated
echo -e "${YELLOW}[2/7]${NC} Checking Prisma client..."
if [ -d "lib/generated/prisma" ]; then
    echo -e "${GREEN}✓${NC} Prisma client exists"
else
    echo -e "${YELLOW}⟳${NC} Generating Prisma client..."
    npx prisma generate
fi

# Run unit tests
if [ "$MODE" != "--e2e-only" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[3/7]${NC} Running Unit Tests..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    echo -e "${YELLOW}→${NC} Geolocation helper tests..."
    npm run test:unit -- __tests__/lib/geolocation.test.ts --silent || true

    echo -e "${YELLOW}→${NC} Component tests..."
    npm run test:unit -- __tests__/components/staff/UsersList.test.tsx --silent || true

    echo -e "${GREEN}✓${NC} Unit tests complete"
fi

# Run API tests
if [ "$MODE" != "--e2e-only" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[4/7]${NC} Running API Tests..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    npm run test:unit -- __tests__/api/staff/user-management.test.ts --silent || true

    echo -e "${GREEN}✓${NC} API tests complete"
fi

# Run integration tests
if [ "$MODE" != "--e2e-only" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[5/7]${NC} Running Integration Tests..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    echo -e "${YELLOW}→${NC} IP tracking tests..."
    npm run test:unit -- __tests__/integration/ip-tracking-login.test.ts --silent || true

    echo -e "${YELLOW}→${NC} Dual-database sync tests..."
    npm run test:unit -- __tests__/integration/dual-database-user-management.test.ts --silent || true

    echo -e "${GREEN}✓${NC} Integration tests complete"
fi

# Run security tests
if [ "$MODE" != "--e2e-only" ] && [ "$MODE" != "--quick" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[6/7]${NC} Running Security Tests..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    npm run test:unit -- __tests__/security/user-management-security.test.ts --silent || true

    echo -e "${GREEN}✓${NC} Security tests complete"
fi

# Run E2E tests
if [ "$MODE" != "--unit-only" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[7/7]${NC} Running E2E Tests (Playwright)..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    # Check if dev server is running
    if curl -s http://localhost:9000/api/health > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} Dev server is running"

        echo -e "${YELLOW}→${NC} User management UI tests..."
        npm run test:e2e -- tests/staff/user-management.spec.ts --reporter=line || true

        echo -e "${YELLOW}→${NC} Workflow tests..."
        npm run test:e2e -- tests/staff/user-management-workflows.spec.ts --reporter=line || true

        echo -e "${GREEN}✓${NC} E2E tests complete"
    else
        echo -e "${YELLOW}⚠${NC} Dev server not running. Skipping E2E tests."
        echo -e "${YELLOW}  Start server with: npm run dev${NC}"
    fi
fi

# Run regression tests
if [ "$MODE" == "--full" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[BONUS]${NC} Running Regression Tests..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    npm run test:unit -- __tests__/regression/user-management-regression.test.ts --silent || true

    echo -e "${GREEN}✓${NC} Regression tests complete"
fi

# Generate coverage report
if [ "$MODE" == "--coverage" ]; then
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${YELLOW}[COVERAGE]${NC} Generating Coverage Report..."
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"

    npm run test:coverage -- \
        --collectCoverageFrom="lib/geolocation.ts" \
        --collectCoverageFrom="app/api/staff/**/*.ts" \
        --collectCoverageFrom="components/staff/users/**/*.tsx"
fi

# Summary
echo ""
echo -e "${BLUE}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║  Test Suite Complete!                                    ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}✓${NC} All user management tests completed"
echo -e "${YELLOW}→${NC} Test files:"
echo -e "  • __tests__/lib/geolocation.test.ts"
echo -e "  • __tests__/api/staff/user-management.test.ts"
echo -e "  • __tests__/integration/ip-tracking-login.test.ts"
echo -e "  • __tests__/integration/dual-database-user-management.test.ts"
echo -e "  • __tests__/security/user-management-security.test.ts"
echo -e "  • __tests__/regression/user-management-regression.test.ts"
echo -e "  • __tests__/components/staff/UsersList.test.tsx"
echo -e "  • tests/staff/user-management.spec.ts (E2E)"
echo -e "  • tests/staff/user-management-workflows.spec.ts (E2E)"
echo ""
echo -e "${BLUE}View detailed results:${NC} Check test output above"
echo -e "${BLUE}Run specific suite:${NC} npm run test:unit -- <test-file>"
echo -e "${BLUE}Generate coverage:${NC} ./scripts/test-user-management.sh --coverage"
echo ""
