#!/bin/bash
# Client Approval System - Production Deployment Script
# Run this script to deploy the client approval system to production

set -e  # Exit on error

echo "===================================================="
echo "  CLIENT APPROVAL SYSTEM - PRODUCTION DEPLOYMENT"
echo "===================================================="
echo ""

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

# Check if we're in the correct directory
if [ ! -f "manage.py" ]; then
    echo -e "${RED}Error: manage.py not found. Please run this script from the project root.${NC}"
    exit 1
fi

echo -e "${YELLOW}Step 1: Checking database connection...${NC}"
python manage.py check --database default
if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Database connection check failed${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Database connection successful${NC}"
echo ""

echo -e "${YELLOW}Step 2: Creating database backup (recommended)...${NC}"
echo "Note: This script does not create a backup automatically."
echo "Please ensure you have a recent database backup before proceeding."
read -p "Continue without backup? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Deployment cancelled by user."
    exit 1
fi
echo -e "${GREEN}✓ Proceeding with deployment${NC}"
echo ""

echo -e "${YELLOW}Step 3: Checking for pending migrations...${NC}"
python manage.py showmigrations users
echo ""

echo -e "${YELLOW}Step 4: Applying migrations...${NC}"
python manage.py migrate users
if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Migration failed${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Migrations applied successfully${NC}"
echo ""

echo -e "${YELLOW}Step 5: Verifying migration...${NC}"
python manage.py check --database default
if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Verification failed${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Verification successful${NC}"
echo ""

echo -e "${YELLOW}Step 6: Collecting static files (if needed)...${NC}"
python manage.py collectstatic --noinput
echo -e "${GREEN}✓ Static files collected${NC}"
echo ""

echo "===================================================="
echo -e "${GREEN}✓ CLIENT APPROVAL SYSTEM DEPLOYED SUCCESSFULLY${NC}"
echo "===================================================="
echo ""
echo "Next steps:"
echo "  1. Test the pending clients page: http://your-domain/users/clients/pending/"
echo "  2. Test approving a client"
echo "  3. Test rejecting a client"
echo "  4. Monitor the audit logs"
echo ""
echo "For admins:"
echo "  - Navigate to the Clients page"
echo "  - Click the 'Pending Approvals' button"
echo "  - Approve or reject clients as needed"
echo ""

