# PostgreSQL Migration Verification Script
Write-Host "=== Jellyfin PostgreSQL Migration Verification ===" -ForegroundColor Cyan
Write-Host ""

# Check if Docker is available
$dockerAvailable = $false
try {
    $null = docker --version 2>&1
    $dockerAvailable = $true
    Write-Host "Docker is available" -ForegroundColor Green
} catch {
    Write-Host "Docker is not available" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "--- Step 1: Check Migration Files ---" -ForegroundColor Cyan

$migrationPath = "src\Jellyfin.Database\Jellyfin.Database.Providers.Postgres\Migrations"
if (Test-Path $migrationPath) {
    $migrations = Get-ChildItem -Path $migrationPath -Filter "*.cs" -Exclude "*Designer.cs", "*Snapshot.cs", "*Factory.cs"
    Write-Host "Found $($migrations.Count) migration(s):" -ForegroundColor Green
    foreach ($migration in $migrations) {
        Write-Host "  - $($migration.Name)" -ForegroundColor Gray
    }
} else {
    Write-Host "Migration path not found" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "--- Step 2: Build PostgreSQL Database Provider ---" -ForegroundColor Cyan

Push-Location "src\Jellyfin.Database\Jellyfin.Database.Providers.Postgres"
try {
    dotnet build --configuration Release
    if ($LASTEXITCODE -eq 0) {
        Write-Host "PostgreSQL provider built successfully" -ForegroundColor Green
    } else {
        Write-Host "Build failed" -ForegroundColor Red
        Pop-Location
        exit 1
    }
} finally {
    Pop-Location
}

Write-Host ""
Write-Host "--- Step 3: List Migrations ---" -ForegroundColor Cyan

Push-Location "src\Jellyfin.Database\Jellyfin.Database.Providers.Postgres"
try {
    Write-Host "Running: dotnet ef migrations list" -ForegroundColor Gray
    dotnet ef migrations list
} finally {
    Pop-Location
}

Write-Host ""
Write-Host "--- Step 4: Generate SQL Script ---" -ForegroundColor Cyan

Push-Location "src\Jellyfin.Database\Jellyfin.Database.Providers.Postgres"
try {
    $sqlOutputPath = "..\..\..\migration-script.sql"
    Write-Host "Generating SQL script..." -ForegroundColor Gray
    dotnet ef migrations script --output $sqlOutputPath --idempotent
    
    if (Test-Path $sqlOutputPath) {
        $sqlContent = Get-Content $sqlOutputPath -Raw
        $lineCount = ($sqlContent -split "`n").Count
        Write-Host "SQL script generated successfully ($lineCount lines)" -ForegroundColor Green
        Write-Host "Location: $((Resolve-Path $sqlOutputPath).Path)" -ForegroundColor Gray
    } else {
        Write-Host "Failed to generate SQL script" -ForegroundColor Red
    }
} catch {
    Write-Host "Error generating SQL script: $_" -ForegroundColor Red
} finally {
    Pop-Location
}

Write-Host ""
Write-Host "=== Verification Complete ===" -ForegroundColor Cyan
