#!/bin/bash

# GCM - Complete Startup Script for CRUD Testing
# Initializes Laravel backend and starts Vue frontend

set -e  # Exit on error

echo "🚀 GCM Backend & Frontend Startup"
echo "=================================="

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# ==========================================
# BACKEND SETUP
# ==========================================

echo -e "${BLUE}[1/5] Setting up Backend (Laravel)${NC}"

cd "$SCRIPT_DIR/backend"

# Generate keys if not already done
if ! grep -q "APP_KEY=base64:" .env 2>/dev/null; then
    echo -e "${YELLOW}Generating application key...${NC}"
    php artisan key:generate
fi

if ! grep -q "JWT_SECRET=" .env 2>/dev/null; then
    echo -e "${YELLOW}Generating JWT secret...${NC}"
    php artisan jwt:secret
fi

# Run migrations
echo -e "${YELLOW}Running database migrations...${NC}"
php artisan migrate --force

# Seed database
echo -e "${YELLOW}Seeding sample data...${NC}"
php artisan db:seed

echo -e "${GREEN}✓ Backend setup complete${NC}"
echo ""

# ==========================================
# START BACKEND SERVER
# ==========================================

echo -e "${BLUE}[2/5] Starting Laravel Development Server${NC}"
echo -e "${YELLOW}Backend running on: http://localhost:8000${NC}"
echo ""

# Start backend in background
php artisan serve --port=8000 > /tmp/laravel.log 2>&1 &
LARAVEL_PID=$!
echo "Laravel PID: $LARAVEL_PID"

# Wait for backend to start
sleep 3

# Check if backend started successfully
if ! kill -0 $LARAVEL_PID 2>/dev/null; then
    echo -e "${RED}✗ Failed to start Laravel server${NC}"
    cat /tmp/laravel.log
    exit 1
fi

echo -e "${GREEN}✓ Laravel server started${NC}"
echo ""

# ==========================================
# FRONTEND SETUP & START
# ==========================================

echo -e "${BLUE}[3/5] Installing Frontend Dependencies${NC}"

cd "$SCRIPT_DIR/frontend"

# Install npm dependencies if not already done
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}Installing npm packages (this may take 1-2 minutes)...${NC}"
    npm install
fi

echo -e "${GREEN}✓ Frontend dependencies ready${NC}"
echo ""

echo -e "${BLUE}[4/5] Starting Vue Development Server${NC}"
echo -e "${YELLOW}Frontend running on: http://localhost:5173${NC}"
echo ""

# Start frontend in background
npm run dev > /tmp/vite.log 2>&1 &
VITE_PID=$!
echo "Vite PID: $VITE_PID"

# Wait for frontend to start
sleep 3

# ==========================================
# SUCCESS - RUNNING SERVERS
# ==========================================

echo ""
echo -e "${GREEN}=================================="
echo "✓ System Started Successfully!"
echo "==================================${NC}"
echo ""
echo -e "${BLUE}📍 Access Points:${NC}"
echo "  Frontend:  ${YELLOW}http://localhost:5173${NC}"
echo "  Backend:   ${YELLOW}http://localhost:8000${NC}"
echo "  API:       ${YELLOW}http://localhost:8000/api${NC}"
echo ""
echo -e "${BLUE}🔐 Test Credentials:${NC}"
echo "  Email:     ${YELLOW}moderator@cms.local${NC}"
echo "  Password:  ${YELLOW}password${NC}"
echo ""
echo -e "${BLUE}📝 Test Accounts (All have password: 'password'):${NC}"
echo "  Admin:               admin@cms.local"
echo "  Moderator:           moderator@cms.local"
echo "  On-Site Team:        site@cms.local"
echo "  Design Team:         design@cms.local"
echo "  Project Consultant:  consultant@cms.local"
echo "  Client:              client@cms.local"
echo ""
echo -e "${BLUE}🧪 Testing CRUD APIs:${NC}"
echo "  1. Login at http://localhost:5173"
echo "  2. Use test credentials"
echo "  3. Try creating/editing/deleting projects"
echo "  4. Check API responses in browser DevTools (F12)"
echo ""
echo -e "${BLUE}📋 Available Operations:${NC}"
echo "  • Create Projects"
echo "  • Submit Progress Reports"
echo "  • Upload Photos"
echo "  • Generate Risk Assessments"
echo "  • View Dashboard"
echo ""
echo -e "${BLUE}🛑 To Stop:${NC}"
echo "  Press Ctrl+C in this terminal"
echo ""

# ==========================================
# KEEP SERVERS RUNNING
# ==========================================

# Function to handle cleanup
cleanup() {
    echo ""
    echo -e "${YELLOW}Shutting down servers...${NC}"
    kill $LARAVEL_PID 2>/dev/null || true
    kill $VITE_PID 2>/dev/null || true
    echo -e "${GREEN}✓ Servers stopped${NC}"
}

# Set trap to cleanup on exit
trap cleanup EXIT

# Wait for both processes
wait
