# Quick Database Command Runner
# Uses settings from db-config.ps1

# Load configuration
. .\db-config.ps1

Write-Host "Quick Database Commands" -ForegroundColor Cyan
Write-Host "Using database: $DB_NAME" -ForegroundColor Yellow
Write-Host ""

# Show menu
Write-Host "Choose an option:" -ForegroundColor Green
Write-Host "1. Run diagnostics (sql\diagnostics.sql)"
Write-Host "2. Check index usage"
Write-Host "3. Check if performance indexes exist"
Write-Host "4. Run all performance indexes script"
Write-Host "5. Custom query"
Write-Host "6. Change database"
Write-Host "7. Exit"
Write-Host ""

$choice = Read-Host "Enter choice (1-7)"

switch ($choice) {
    "1" {
        Write-Host "Running diagnostics..." -ForegroundColor Yellow
        Invoke-PSQL -File "sql\diagnostics.sql" -OutputFile "diagnostics_$(Get-Date -Format 'yyyy-MM-dd_HHmmss').txt"
        Write-Host "✓ Results saved to diagnostics_*.txt" -ForegroundColor Green
    }
    "2" {
        Write-Host "Checking index usage..." -ForegroundColor Yellow
        $query = "SELECT indexname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes WHERE schemaname = 'library' AND indexname LIKE 'idx_%' ORDER BY idx_scan DESC;"
        Invoke-PSQL -Query $query
    }
    "3" {
        Write-Host "Checking performance indexes..." -ForegroundColor Yellow
        $query = "SELECT COUNT(*) as perf_index_count FROM pg_indexes WHERE schemaname = 'library' AND indexname IN ('baseitems_communityrating_idx', 'baseitems_datecreated_idx', 'baseitems_datemodified_idx', 'baseitems_parentid_idx', 'baseitems_premieredate_idx', 'baseitems_productionyear_idx', 'baseitems_seriespresentationuniquekey_idx', 'baseitems_sortname_idx', 'baseitems_topparentid_idx');"
        Invoke-PSQL -Query $query
    }
    "4" {
        Write-Host "Running all performance indexes script..." -ForegroundColor Yellow
        Invoke-PSQL -File "sql\all_performance_indexes.sql"
        Write-Host "✓ Script complete" -ForegroundColor Green
    }
    "5" {
        $query = Read-Host "Enter SQL query"
        Invoke-PSQL -Query $query
    }
    "6" {
        Write-Host ""
        Write-Host "Current database: $DB_NAME" -ForegroundColor Yellow
        Write-Host ""
        Write-Host "To change database:" -ForegroundColor Cyan
        Write-Host "1. Edit db-config.ps1" -ForegroundColor Gray
        Write-Host "2. Change the line: `$DB_NAME = `"jellyfin_testsdata`"" -ForegroundColor Gray
        Write-Host "3. Save and run: . .\db-config.ps1" -ForegroundColor Gray
        Write-Host ""
    }
    "7" {
        Write-Host "Goodbye!" -ForegroundColor Cyan
        exit
    }
    default {
        Write-Host "Invalid choice" -ForegroundColor Red
    }
}
