#!/bin/bash

# Production deployment script for rollover enhancements
# Handles migration issues and deploys the new rollover functionality

echo "=== Production Deployment: Rollover Enhancements ==="
echo "This script will deploy the enhanced rollover functionality with date field"
echo "and add Complete History buttons to client popup and loan detail pages."
echo ""

# Set error handling
set -e

# Function to handle errors
handle_error() {
    echo "ERROR: Deployment failed at line $1"
    echo "Please check the error above and try again."
    exit 1
}

# Set trap for error handling
trap 'handle_error $LINENO' ERR

# Navigate to project directory (adjust path as needed)
cd /home/acbptxvs/public_html/branchbusinessadvance.co.ke

echo "=== Step 1: Activating Virtual Environment ==="
source /home/acbptxvs/virtualenv/public_html/branchbusinessadvance.co.ke/3.13/bin/activate

echo "=== Step 2: Checking Current Migration Status ==="
python manage.py showmigrations users | head -20
python manage.py showmigrations loans | head -20

echo ""
echo "=== Step 3: Fixing Migration History ==="
# Check if we need to fix migration history
python -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
with connection.cursor() as cursor:
    cursor.execute(\"SELECT COUNT(*) FROM django_migrations WHERE app = 'users' AND name = '0011_manual_add_is_default'\")
    has_0011 = cursor.fetchone()[0] > 0
    
    cursor.execute(\"SELECT COUNT(*) FROM django_migrations WHERE app = 'users' AND name = '0010_add_enhanced_permissions'\")
    has_0010 = cursor.fetchone()[0] > 0
    
    if has_0011 and not has_0010:
        print('Fixing inconsistent migration history...')
        cursor.execute(\"DELETE FROM django_migrations WHERE app = 'users' AND name = '0011_manual_add_is_default'\")
        print('Removed problematic migration record')
    else:
        print('Migration history appears consistent')
"

echo ""
echo "=== Step 4: Adding rollover_date Column ==="
python -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
with connection.cursor() as cursor:
    # Check if column already exists
    cursor.execute(\"\"\"
        SELECT COUNT(*) 
        FROM information_schema.columns 
        WHERE table_schema = DATABASE() 
        AND table_name = 'rollover_requests' 
        AND column_name = 'rollover_date'
    \"\"\")
    column_exists = cursor.fetchone()[0] > 0
    
    if not column_exists:
        print('Adding rollover_date column...')
        cursor.execute(\"\"\"
            ALTER TABLE rollover_requests 
            ADD COLUMN rollover_date DATE NULL 
            COMMENT 'Preferred rollover date'
        \"\"\")
        print('Added rollover_date column successfully')
    else:
        print('rollover_date column already exists')
"

echo ""
echo "=== Step 5: Creating Migration Record ==="
python -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
with connection.cursor() as cursor:
    # Check if migration record already exists
    cursor.execute(\"\"\"
        SELECT COUNT(*) 
        FROM django_migrations 
        WHERE app = 'loans' AND name = '0018_add_rollover_date_field'
    \"\"\")
    migration_exists = cursor.fetchone()[0] > 0
    
    if not migration_exists:
        print('Creating migration record...')
        cursor.execute(\"\"\"
            INSERT INTO django_migrations (app, name, applied) 
            VALUES ('loans', '0018_add_rollover_date_field', NOW())
        \"\"\")
        print('Created migration record successfully')
    else:
        print('Migration record already exists')
"

echo ""
echo "=== Step 6: Running Django Migrations ==="
python manage.py migrate --noinput

echo ""
echo "=== Step 7: Verifying Deployment ==="
python -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
from loans.models import RolloverRequest

# Check if rollover_date column exists
with connection.cursor() as cursor:
    cursor.execute(\"\"\"
        SELECT COUNT(*) 
        FROM information_schema.columns 
        WHERE table_schema = DATABASE() 
        AND table_name = 'rollover_requests' 
        AND column_name = 'rollover_date'
    \"\"\")
    column_exists = cursor.fetchone()[0] > 0

if column_exists:
    print('SUCCESS: rollover_date column is present')
    
    # Test the model
    fields = [field.name for field in RolloverRequest._meta.fields]
    if 'rollover_date' in fields:
        print('SUCCESS: RolloverRequest model has rollover_date field')
        print('SUCCESS: Rollover enhancements deployed successfully!')
    else:
        print('ERROR: RolloverRequest model missing rollover_date field')
        exit(1)
else:
    print('ERROR: rollover_date column is missing')
    exit(1)
"

echo ""
echo "=== Deployment Complete ==="
echo "SUCCESS: All rollover enhancements have been deployed!"
echo "Features deployed:"
echo "  - Enhanced rollover form with date field"
echo "  - Complete History button in client popup"
echo "  - Complete History button in loan detail pages"
echo "  - Database migration for rollover_date field"
echo ""
echo "The system is now ready with the enhanced rollover functionality!"
