#!/bin/bash
# Quick Database Deployment Script for Unix/Linux/Mac

echo "=========================================="
echo "DATABASE DEPLOYMENT SCRIPT"
echo "=========================================="

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if virtual environment is activated
if [ -z "$VIRTUAL_ENV" ]; then
    echo -e "${YELLOW}⚠ Warning: Virtual environment not activated${NC}"
    echo "Attempting to activate..."
    if [ -f "venv/bin/activate" ]; then
        source venv/bin/activate
    elif [ -f "env/bin/activate" ]; then
        source env/bin/activate
    fi
fi

# Step 1: Check database connection
echo -e "\n${GREEN}=== Checking Database Connection ===${NC}"
python -c "import django; django.setup(); from django.db import connection; connection.ensure_connection(); print('✓ Connected')" 2>/dev/null
if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Database connection failed${NC}"
    exit 1
fi

# Step 2: Show pending migrations
echo -e "\n${GREEN}=== Checking Pending Migrations ===${NC}"
python manage.py showmigrations --plan | grep "\[ \]" | head -10

# Step 3: Apply migrations
echo -e "\n${GREEN}=== Applying Migrations ===${NC}"
python manage.py migrate --noinput
if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Migration failed${NC}"
    exit 1
fi

# Step 4: Collect static files
echo -e "\n${GREEN}=== Collecting Static Files ===${NC}"
python manage.py collectstatic --noinput --clear

# Step 5: Run system checks
echo -e "\n${GREEN}=== Running System Checks ===${NC}"
python manage.py check

echo -e "\n${GREEN}=========================================="
echo "✅ DEPLOYMENT COMPLETED"
echo "==========================================${NC}"
