#!/bin/bash

echo "🚀 Starting Atahan(Baclend) (Standalone Mode)..."
echo ""

# Check if .env exists
if [ ! -f .env ]; then
    echo "❌ .env file not found!"
    echo "Please create .env file with required configuration."
    exit 1
fi

# Read config from .env for display purposes only
PORT=$(grep '^PORT=' .env | cut -d'=' -f2)
DB_HOST=$(grep '^DB_HOST=' .env | cut -d'=' -f2)
DB_PORT=$(grep '^DB_PORT=' .env | cut -d'=' -f2)
DB_NAME=$(grep '^DB_NAME=' .env | cut -d'=' -f2)
DB_USER=$(grep '^DB_USER=' .env | cut -d'=' -f2)
DB_PASSWORD=$(grep '^DB_PASSWORD=' .env | cut -d'=' -f2)
REDIS_HOST=$(grep '^REDIS_HOST=' .env | cut -d'=' -f2)
REDIS_PORT=$(grep '^REDIS_PORT=' .env | cut -d'=' -f2)
REDIS_PASSWORD=$(grep '^REDIS_PASSWORD=' .env | cut -d'=' -f2)

echo "📋 Configuration:"
echo "   - Server Port: ${PORT:-8080}"
echo "   - PostgreSQL: ${DB_HOST}:${DB_PORT}/${DB_NAME} (user: ${DB_USER})"
echo "   - Redis: ${REDIS_HOST}:${REDIS_PORT}"
echo ""

# Check PostgreSQL connection
echo "🔍 Checking PostgreSQL connection..."
if command -v psql &> /dev/null; then
    PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c "SELECT 1;" &> /dev/null
    if [ $? -eq 0 ]; then
        echo "✅ PostgreSQL connection successful"
    else
        echo "⚠️  Cannot connect to PostgreSQL at ${DB_HOST}:${DB_PORT}"
        echo "   Make sure PostgreSQL is running and accessible"
    fi
else
    echo "⚠️  psql not found, skipping PostgreSQL connection test"
fi

# Check Redis connection
echo "🔍 Checking Redis connection..."
if command -v redis-cli &> /dev/null; then
    redis-cli -h $REDIS_HOST -p $REDIS_PORT -a $REDIS_PASSWORD --no-auth-warning PING &> /dev/null
    if [ $? -eq 0 ]; then
        echo "✅ Redis connection successful"
    else
        echo "⚠️  Cannot connect to Redis at ${REDIS_HOST}:${REDIS_PORT}"
        echo "   Make sure Redis is running and accessible"
    fi
else
    echo "⚠️  redis-cli not found, skipping Redis connection test"
fi

echo ""
echo "🔧 Building application..."
go build -o main .

if [ $? -ne 0 ]; then
    echo "❌ Build failed!"
    exit 1
fi

echo "✅ Build successful!"
echo ""
echo "🚀 Starting server on port ${PORT}..."
echo ""
echo "📍 Access points:"
echo "   - API: http://localhost:${PORT}"
echo "   - Swagger: http://localhost:${PORT}/v1/docs/index.html"
echo ""
echo "Press Ctrl+C to stop the server"
echo ""

./main
