#!/bin/bash

# Emergency deployment script for borrower_id column fix
# This script will fix the missing borrower_id column in the receipts table

echo "=== Emergency Fix for receipts.borrower_id Column ==="
echo "Timestamp: $(date)"
echo

# Check if we're in the right directory
if [ ! -f "manage.py" ]; then
    echo "❌ Error: manage.py not found. Please run this script from the project root directory."
    exit 1
fi

# Create backup before making changes
echo "📦 Creating database backup..."
BACKUP_FILE="backup_receipts_fix_$(date +%Y%m%d_%H%M%S).sql"

# Backup just the receipts table structure and data
python3 -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RuralPoint.settings')
django.setup()
from django.core.management import call_command
call_command('dumpdata', 'utils.Receipt', '--output=$BACKUP_FILE.json', '--indent=2')
print('✓ Receipts data backed up to $BACKUP_FILE.json')
"

# Run the fix script
echo
echo "🔧 Running borrower_id column fix..."
python3 fix_receipts_borrower_id_production.py

# Check if the fix was successful
if [ $? -eq 0 ]; then
    echo
    echo "✅ Fix completed successfully!"
    echo
    echo "📋 Next steps:"
    echo "1. Test the loan repayment functionality"
    echo "2. Check the application logs for any errors"
    echo "3. Monitor the system for a few minutes"
    echo
    echo "🔗 Test URL: https://branchbusinessadvance.co.ke/loans/[loan-id]/repay/"
    echo
else
    echo
    echo "❌ Fix failed! Check the logs for details."
    echo "📄 Log file: receipts_borrower_id_fix.log"
    echo
    exit 1
fi

echo "=== Fix Deployment Complete ==="