#!/bin/bash

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

# Function to kill background processes on exit
cleanup() {
    echo -e "\n${YELLOW}🛑 Stopping services...${NC}"
    kill $(jobs -p) 2>/dev/null
    exit
}

trap cleanup SIGINT SIGTERM

# Header
clear
echo -e "${CYAN}"
echo "╔══════════════════════════════════════════════╗"
echo "║         🐴 GoHorse Jobs - Dev Server         ║"
echo "╚══════════════════════════════════════════════╝"
echo -e "${NC}"

# Interactive menu
echo -e "${GREEN}Select an option:${NC}\n"
echo -e "  ${CYAN}── Services ──${NC}"
echo -e "  ${YELLOW}1)${NC} 🚀 Start (Frontend + Backend)"
echo -e "  ${YELLOW}2)${NC} 🌱 Start with Seed (Reset DB + Seed + Start)"
echo -e "  ${YELLOW}3)${NC} 📦 Start All (Frontend + Backend + Backoffice)"
echo -e ""
echo -e "  ${CYAN}── Database ──${NC}"
echo -e "  ${YELLOW}4)${NC} 🗄️  Run Migrations"
echo -e "  ${YELLOW}5)${NC} 🌿 Seed Only (append data)"
echo -e "  ${YELLOW}6)${NC} 🔄 Seed Reset (drop all + seed fresh)"
echo -e ""
echo -e "  ${CYAN}── Testing ──${NC}"
echo -e "  ${YELLOW}7)${NC} 🧪 Run Tests (Backend E2E)"
echo -e "  ${YELLOW}0)${NC} ❌ Exit"
echo -e ""
echo -e "  ${CYAN}── Fast Options ──${NC}"
echo -e "  ${YELLOW}8)${NC} ⚡ Seed Reset LITE (skip 153k cities)"
echo -e "  ${YELLOW}9)${NC} 🔬 Run All Tests (Backend + Frontend)"
echo -e ""
echo -e "  ${CYAN}── Docker/Deploy ──${NC}"
echo -e "  ${YELLOW}a)${NC} 🐳 Build Docker Images"
echo -e "  ${YELLOW}b)${NC} 🚀 Build & Push to Forgejo"
echo ""
read -p "Enter option [0-9,a,b]: " choice

case $choice in
    1)
        echo -e "\n${GREEN}🚀 Starting Development Environment...${NC}\n"
        
        # Backend
        echo -e "${BLUE}🔹 Checking Backend...${NC}"
        cd backend && go mod tidy
        if command -v swag &> /dev/null; then
            echo -e "${BLUE}🔹 Generating Swagger Docs...${NC}"
            swag init -g cmd/api/main.go --parseDependency --parseInternal 2>/dev/null
        fi
        cd ..
        
        # Frontend deps
        if [ ! -d "frontend/node_modules" ]; then
            echo -e "${BLUE}🔹 Installing Frontend Dependencies...${NC}"
            cd frontend && npm install && cd ..
        fi
        
        # Start services
        echo -e "${BLUE}🔹 Starting Backend on port 8521...${NC}"
        (cd backend && go run cmd/api/main.go) &
        BACKEND_PID=$!
        sleep 2
        
        echo -e "${BLUE}🔹 Starting Frontend on port 8963...${NC}"
        (cd frontend && npm run dev -- -p 8963) &
        FRONTEND_PID=$!
        
        echo -e "\n${GREEN}✅ Services running:${NC}"
        echo -e "   ${CYAN}Backend:${NC}  http://localhost:8521"
        echo -e "   ${CYAN}Frontend:${NC} http://localhost:8963"
        echo -e "   ${CYAN}Swagger:${NC}  http://localhost:8521/swagger/index.html"
        echo ""
        
        wait $BACKEND_PID $FRONTEND_PID
        ;;
        
    2)
        echo -e "\n${GREEN}🌱 Starting with Database Reset & Seed...${NC}\n"
        
        # Backend prep
        echo -e "${BLUE}🔹 Checking Backend...${NC}"
        cd backend && go mod tidy
        if command -v swag &> /dev/null; then
            swag init -g cmd/api/main.go --parseDependency --parseInternal 2>/dev/null
        fi
        cd ..
        
        # Seeder deps
        cd seeder-api
        if [ ! -d "node_modules" ]; then
            echo -e "${BLUE}🔹 Installing Seeder Dependencies...${NC}"
            npm install
        fi
        
        echo -e "${YELLOW}🔹 Resetting Database...${NC}"
        npm run seed:reset
        cd ..
        
        # Start backend
        echo -e "${BLUE}🔹 Starting Backend...${NC}"
        (cd backend && go run cmd/api/main.go) &
        BACKEND_PID=$!
        
        echo -e "${YELLOW}⏳ Waiting for Backend...${NC}"
        sleep 5
        
        # Seed
        echo -e "${BLUE}🔹 Seeding Database (30 companies, 990 jobs)...${NC}"
        cd seeder-api && npm run seed && cd ..
        
        # Frontend
        if [ ! -d "frontend/node_modules" ]; then
            cd frontend && npm install && cd ..
        fi
        
        echo -e "${BLUE}🔹 Starting Frontend...${NC}"
        (cd frontend && npm run dev -- -p 8963) &
        FRONTEND_PID=$!
        
        echo -e "\n${GREEN}✅ Services running with fresh data!${NC}"
        echo -e "   ${CYAN}Backend:${NC}  http://localhost:8521"
        echo -e "   ${CYAN}Frontend:${NC} http://localhost:8963"
        echo ""
        
        wait $BACKEND_PID $FRONTEND_PID
        ;;
        
    3)
        echo -e "\n${GREEN}📦 Starting All Services (Including Backoffice)...${NC}\n"
        
        # Backend
        cd backend && go mod tidy && cd ..
        
        # Dependencies
        [ ! -d "frontend/node_modules" ] && (cd frontend && npm install && cd ..)
        [ ! -d "backoffice/node_modules" ] && (cd backoffice && npm install && cd ..)
        
        echo -e "${BLUE}🔹 Starting Backend on port 8521...${NC}"
        (cd backend && go run cmd/api/main.go) &
        sleep 2
        
        echo -e "${BLUE}🔹 Starting Frontend on port 8963...${NC}"
        (cd frontend && npm run dev -- -p 8963) &
        
        echo -e "${BLUE}🔹 Starting Backoffice on port 3001...${NC}"
        (cd backoffice && npm run start:dev) &
        
        echo -e "\n${GREEN}✅ All services running:${NC}"
        echo -e "   ${CYAN}Backend:${NC}    http://localhost:8521"
        echo -e "   ${CYAN}Frontend:${NC}   http://localhost:8963"
        echo -e "   ${CYAN}Backoffice:${NC} http://localhost:3001"
        echo -e "   ${CYAN}Swagger:${NC}    http://localhost:3001/api/docs"
        echo ""
        
        wait
        ;;
        
    4)
        echo -e "\n${GREEN}🗄️  Running Migrations...${NC}\n"
        cd seeder-api
        [ ! -d "node_modules" ] && npm install
        npm run migrate
        ;;
        
    5)
        echo -e "\n${GREEN}🌿 Seeding Database Only...${NC}\n"
        cd seeder-api
        [ ! -d "node_modules" ] && npm install
        npm run seed
        echo -e "\n${GREEN}✅ Seeding completed!${NC}"
        ;;
        
    6)
        echo -e "\n${GREEN}🔄 Resetting Database & Seeding Fresh...${NC}\n"
        cd seeder-api
        [ ! -d "node_modules" ] && npm install
        
        echo -e "${YELLOW}⚠️  This will DROP all tables and recreate!${NC}"
        read -p "Are you sure? [y/N]: " confirm
        
        if [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]]; then
            echo -e "\n${BLUE}🔹 Step 1/3: Dropping all tables...${NC}"
            npm run seed:reset
            
            echo -e "\n${BLUE}🔹 Step 2/3: Running migrations...${NC}"
            npm run migrate
            
            echo -e "\n${BLUE}🔹 Step 3/3: Seeding data...${NC}"
            npm run seed
            
            echo -e "\n${GREEN}✅ Database fully reset and seeded!${NC}"
        else
            echo -e "${YELLOW}Cancelled.${NC}"
        fi
        ;;
        
    7)
        echo -e "\n${GREEN}🧪 Running Backend E2E Tests...${NC}\n"
        cd backend && go test -tags=e2e -v ./tests/e2e/... 2>&1
        echo -e "\n${GREEN}✅ Tests completed!${NC}"
        ;;

    8)
        echo -e "\n${GREEN}⚡ Fast Reset - Seed LITE (no cities)...${NC}\n"
        cd seeder-api
        [ ! -d "node_modules" ] && npm install
        
        echo -e "${YELLOW}⚠️  This will DROP all tables and recreate (WITHOUT 153k cities)${NC}"
        read -p "Are you sure? [y/N]: " confirm
        
        if [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]]; then
            echo -e "\n${BLUE}🔹 Step 1/3: Dropping all tables...${NC}"
            npm run seed:reset
            
            echo -e "\n${BLUE}🔹 Step 2/3: Running migrations...${NC}"
            npm run migrate
            
            echo -e "\n${BLUE}🔹 Step 3/3: Seeding data (LITE - no cities)...${NC}"
            npm run seed:lite
            
            echo -e "\n${GREEN}✅ Database reset (LITE) completed! Cities skipped for speed.${NC}"
        else
            echo -e "${YELLOW}Cancelled.${NC}"
        fi
        ;;

    9)
        echo -e "\n${GREEN}🔬 Running All Tests...${NC}\n"
        
        echo -e "${BLUE}🔹 Backend Unit Tests...${NC}"
        cd backend && go test -v ./... -count=1 2>&1 | tail -20
        BACKEND_RESULT=$?
        cd ..
        
        echo -e "\n${BLUE}🔹 Backend E2E Tests...${NC}"
        cd backend && go test -tags=e2e -v ./tests/e2e/... 2>&1
        E2E_RESULT=$?
        cd ..
        
        if [ -d "frontend/node_modules" ]; then
            echo -e "\n${BLUE}🔹 Frontend Tests...${NC}"
            cd frontend && npm test -- --passWithNoTests 2>&1
            FRONTEND_RESULT=$?
            cd ..
        else
            echo -e "${YELLOW}⚠️  Frontend node_modules not found, skipping frontend tests${NC}"
            FRONTEND_RESULT=0
        fi
        
        echo -e "\n${GREEN}═══════════════════════════════════════${NC}"
        if [ $BACKEND_RESULT -eq 0 ] && [ $E2E_RESULT -eq 0 ] && [ $FRONTEND_RESULT -eq 0 ]; then
            echo -e "${GREEN}✅ All tests passed!${NC}"
        else
            echo -e "${RED}❌ Some tests failed${NC}"
        fi
        ;;
        
    0)
        echo -e "${YELLOW}Bye! 👋${NC}"
        exit 0
        ;;
        
    *)
        echo -e "${RED}Invalid option. Exiting.${NC}"
        exit 1
        ;;

    a)
        echo -e "\n${GREEN}🐳 Building Docker Images...${NC}\n"
        
        REGISTRY="forgejo-gru.rede5.com.br/rede5"
        
        echo -e "${BLUE}🔹 Building Backend...${NC}"
        podman build -t $REGISTRY/gohorsejobs-backend:latest -f backend/Dockerfile backend/
        
        echo -e "\n${BLUE}🔹 Building Frontend...${NC}"
        podman build -t $REGISTRY/gohorsejobs-frontend:latest -f frontend/Dockerfile frontend/
        
        echo -e "\n${BLUE}🔹 Building Seeder...${NC}"
        podman build -t $REGISTRY/gohorsejobs-seeder:latest -f seeder-api/Dockerfile seeder-api/
        
        echo -e "\n${GREEN}✅ All images built successfully!${NC}"
        echo -e "   ${CYAN}Backend:${NC}  $REGISTRY/gohorsejobs-backend:latest"
        echo -e "   ${CYAN}Frontend:${NC} $REGISTRY/gohorsejobs-frontend:latest"
        echo -e "   ${CYAN}Seeder:${NC}   $REGISTRY/gohorsejobs-seeder:latest"
        ;;
        
    b)
        echo -e "\n${GREEN}🚀 Building & Pushing to Forgejo Registry...${NC}\n"
        
        REGISTRY="forgejo-gru.rede5.com.br/rede5"
        
        # Check if logged in
        echo -e "${BLUE}🔹 Checking registry login...${NC}"
        if ! podman login --get-login $REGISTRY 2>/dev/null; then
            echo -e "${YELLOW}⚠️  Not logged in. Please enter your credentials:${NC}"
            read -p "Username: " REGISTRY_USER
            read -s -p "Password/Token: " REGISTRY_PASS
            echo ""
            podman login forgejo-gru.rede5.com.br -u "$REGISTRY_USER" -p "$REGISTRY_PASS"
        fi
        
        echo -e "\n${BLUE}🔹 Building Backend...${NC}"
        podman build -t $REGISTRY/gohorsejobs-backend:latest -f backend/Dockerfile backend/
        
        echo -e "\n${BLUE}🔹 Building Frontend...${NC}"
        podman build -t $REGISTRY/gohorsejobs-frontend:latest -f frontend/Dockerfile frontend/
        
        echo -e "\n${BLUE}🔹 Building Seeder...${NC}"
        podman build -t $REGISTRY/gohorsejobs-seeder:latest -f seeder-api/Dockerfile seeder-api/
        
        echo -e "\n${BLUE}🔹 Pushing Backend...${NC}"
        podman push $REGISTRY/gohorsejobs-backend:latest
        
        echo -e "\n${BLUE}🔹 Pushing Frontend...${NC}"
        podman push $REGISTRY/gohorsejobs-frontend:latest
        
        echo -e "\n${BLUE}🔹 Pushing Seeder...${NC}"
        podman push $REGISTRY/gohorsejobs-seeder:latest
        
        echo -e "\n${GREEN}✅ All images built and pushed!${NC}"
        echo -e "   ${CYAN}Registry:${NC} $REGISTRY"
        echo -e "   ${CYAN}Images:${NC}   gohorsejobs-backend, gohorsejobs-frontend, gohorsejobs-seeder"
        ;;
esac

