#!/bin/bash
# Veza Backend API - Development Environment Setup Script

set -e

echo "🚀 Veza Backend API - Development Setup"
echo "======================================"
echo ""

# Check if .env file exists
if [ ! -f .env ]; then
    echo "📝 Creating .env file from .env.example..."
    cp config/env.example .env 2>/dev/null || echo "⚠️  No .env.example found, please create .env manually"
    echo "✏️  Please edit .env file with your configuration"
fi

# Check if PostgreSQL is running
echo "🔍 Checking PostgreSQL..."
if ! pg_isready -h localhost -p 5432 >/dev/null 2>&1; then
    echo "⚠️  PostgreSQL is not running on localhost:5432"
    echo "   Please start PostgreSQL before continuing"
    echo ""
    echo "   On Fedora/RHEL: sudo systemctl start postgresql"
    echo "   On Ubuntu/Debian: sudo systemctl start postgresql"
    echo "   On macOS: brew services start postgresql"
    exit 1
fi
echo "✅ PostgreSQL is running"

# Check if Redis is running
echo "🔍 Checking Redis..."
if ! redis-cli ping >/dev/null 2>&1; then
    echo "⚠️  Redis is not running on localhost:6379"
    echo "   Please start Redis before continuing"
    echo ""
    echo "   On Fedora/RHEL: sudo systemctl start redis"
    echo "   On Ubuntu/Debian: sudo systemctl start redis-server"
    echo "   On macOS: brew services start redis"
    exit 1
fi
echo "✅ Redis is running"

# Check if Go is installed
echo "🔍 Checking Go installation..."
if ! command -v go &> /dev/null; then
    echo "❌ Go is not installed"
    echo "   Please install Go 1.21 or higher"
    echo "   Download from: https://golang.org/dl/"
    exit 1
fi
go_version=$(go version | awk '{print $3}')
echo "✅ Go is installed: $go_version"

# Create database if it doesn't exist
echo "🔍 Checking database..."
export PGPASSWORD="${POSTGRES_PASSWORD:-password}"
export PGHOST="${POSTGRES_HOST:-localhost}"
export PGPORT="${POSTGRES_PORT:-5432}"
export PGUSER="${POSTGRES_USER:-veza}"

if psql -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw veza_db; then
    echo "✅ Database 'veza_db' already exists"
else
    echo "📝 Creating database 'veza_db'..."
    createdb veza_db 2>/dev/null || echo "⚠️  Could not create database, please create it manually:"
    echo "   createdb veza_db"
fi

# Install dependencies
echo "📦 Installing Go dependencies..."
cd "$(dirname "$0")/.." || exit
go mod download
go mod tidy

# Build the application
echo "🔨 Building application..."
go build -o bin/veza-backend-api ./main.go || echo "⚠️  Build failed, you can try again later"

echo ""
echo "✅ Development environment setup complete!"
echo ""
echo "📋 Next steps:"
echo "   1. Edit .env file with your database credentials"
echo "   2. Run migrations: ./bin/veza-backend-api (will auto-migrate)"
echo "   3. Start the server: go run main.go"
echo ""
echo "📚 Documentation:"
echo "   - API docs: docs/api/"
echo "   - Architecture: docs/architecture/"
echo "   - Development guide: docs/guides/DEVELOPER_GUIDE.md"
echo ""
