#!/bin/bash

# Project Progress Tracker Development Script
# This script runs both frontend and backend servers for development

echo "=== Project Progress Tracker Development Startup ==="
echo "Starting PostgreSQL database, frontend and backend servers..."

# Check if PostgreSQL is running
if ! pg_isready > /dev/null 2>&1; then
    echo "PostgreSQL is not running. Please start PostgreSQL first."
    echo "You can typically start it with: sudo service postgresql start"
    exit 1
fi

# Create database if it doesn't exist
echo "Checking database..."
if ! psql -lqt | cut -d \| -f 1 | grep -qw project_tracker; then
    echo "Creating database 'project_tracker'..."
    createdb project_tracker
    
    # Initialize database schema
    echo "Initializing database schema..."
    psql -d project_tracker -f backend/src/config/init.sql
else
    echo "Database 'project_tracker' already exists."
fi

# Start backend and frontend in separate terminals
echo "Starting backend server..."
cd backend && npm run dev &
BACKEND_PID=$!

echo "Starting frontend server..."
cd frontend && npm start &
FRONTEND_PID=$!

# Function to handle script termination
function cleanup {
    echo "Stopping servers..."
    kill $BACKEND_PID
    kill $FRONTEND_PID
    echo "Servers stopped."
    exit
}

# Register the cleanup function for SIGINT (Ctrl+C)
trap cleanup SIGINT

echo "=== Development servers are running ==="
echo "Backend server: http://localhost:5000"
echo "Frontend server: http://localhost:3000"
echo "Press Ctrl+C to stop both servers."

# Wait for user to stop the script
wait
