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

Write-Host "=== Emergency Fix for receipts.borrower_id Column ===" -ForegroundColor Yellow
Write-Host "Timestamp: $(Get-Date)" -ForegroundColor Gray
Write-Host ""

# Check if we're in the right directory
if (-not (Test-Path "manage.py")) {
    Write-Host "❌ Error: manage.py not found. Please run this script from the project root directory." -ForegroundColor Red
    exit 1
}

# Create backup before making changes
Write-Host "📦 Creating database backup..." -ForegroundColor Blue
$BackupFile = "backup_receipts_fix_$(Get-Date -Format 'yyyyMMdd_HHmmss')"

# Run the fix script
Write-Host ""
Write-Host "🔧 Running borrower_id column fix..." -ForegroundColor Blue
python fix_receipts_borrower_id_production.py

# Check if the fix was successful
if ($LASTEXITCODE -eq 0) {
    Write-Host ""
    Write-Host "✅ Fix completed successfully!" -ForegroundColor Green
    Write-Host ""
    Write-Host "📋 Next steps:" -ForegroundColor Yellow
    Write-Host "1. Test the loan repayment functionality" -ForegroundColor White
    Write-Host "2. Check the application logs for any errors" -ForegroundColor White
    Write-Host "3. Monitor the system for a few minutes" -ForegroundColor White
    Write-Host ""
    Write-Host "🔗 Test URL: https://branchbusinessadvance.co.ke/loans/[loan-id]/repay/" -ForegroundColor Cyan
    Write-Host ""
} else {
    Write-Host ""
    Write-Host "❌ Fix failed! Check the logs for details." -ForegroundColor Red
    Write-Host "📄 Log file: receipts_borrower_id_fix.log" -ForegroundColor Yellow
    Write-Host ""
    exit 1
}

Write-Host "=== Fix Deployment Complete ===" -ForegroundColor Yellow