# Generate PostgreSQL Migrations Script
# This script creates PostgreSQL EF Core migrations from the Jellyfin DbContext

[CmdletBinding()]
param(
    [string]$ConnectionString = "Host=localhost;Database=jellyfin_test;Username=jellyfin;Password=jellyfin",
    [switch]$TestMigration
)

$ErrorActionPreference = "Stop"

# Get paths
$WorkspaceRoot = "E:\Projects\pgsql-jellyfin"
$PostgresProviderPath = Join-Path $WorkspaceRoot "src\Jellyfin.Database\Jellyfin.Database.Providers.Postgres"
$MigrationsPath = Join-Path $PostgresProviderPath "Migrations"

Write-Host "Checking prerequisites..." -ForegroundColor Cyan

# Check if dotnet-ef is installed
try {
    $efVersion = dotnet ef --version 2>&1
    Write-Host "dotnet-ef installed: $efVersion" -ForegroundColor Green
} catch {
    Write-Host "dotnet-ef not found. Installing..." -ForegroundColor Red
    dotnet tool install --global dotnet-ef
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to install dotnet-ef"
    }
}

# Check if PostgreSQL provider project exists
if (-not (Test-Path $PostgresProviderPath)) {
    throw "PostgreSQL provider project not found at: $PostgresProviderPath"
}

Write-Host "PostgreSQL provider path: $PostgresProviderPath" -ForegroundColor Cyan

# Navigate to PostgreSQL provider directory
Push-Location $PostgresProviderPath

try {
    Write-Host "`nBuilding project..." -ForegroundColor Cyan
    dotnet build --configuration Release
    if ($LASTEXITCODE -ne 0) {
        throw "Build failed"
    }

    Write-Host "`nChecking existing migrations..." -ForegroundColor Cyan
    $existingMigrations = Get-ChildItem -Path $MigrationsPath -Filter "*.cs" -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -notlike "*Designer.cs" -and $_.Name -notlike "*Factory.cs" }
    
    if ($existingMigrations) {
        Write-Host "Found $($existingMigrations.Count) existing migration(s):" -ForegroundColor Yellow
        $existingMigrations | ForEach-Object { Write-Host "   - $($_.Name)" -ForegroundColor Yellow }
        
        $response = Read-Host "`nRemove existing migrations and create fresh InitialCreate? (y/N)"
        if ($response -eq 'y' -or $response -eq 'Y') {
            Write-Host "Removing existing migrations..." -ForegroundColor Yellow
            $existingMigrations | Remove-Item -Force
            $designerFiles = Get-ChildItem -Path $MigrationsPath -Filter "*Designer.cs" -ErrorAction SilentlyContinue
            $designerFiles | Remove-Item -Force
            Write-Host "Existing migrations removed" -ForegroundColor Green
        } else {
            Write-Host "Cancelled by user" -ForegroundColor Red
            return
        }
    }

    Write-Host "`nGenerating InitialCreate migration for PostgreSQL..." -ForegroundColor Cyan
    Write-Host "   This may take a minute..." -ForegroundColor Gray
    
    dotnet ef migrations add InitialCreate --context JellyfinDbContext --output-dir Migrations --verbose
    
    if ($LASTEXITCODE -ne 0) {
        throw "Migration generation failed"
    }

    Write-Host "PostgreSQL migration generated successfully!" -ForegroundColor Green

    # List generated files
    $generatedFiles = Get-ChildItem -Path $MigrationsPath -Filter "*InitialCreate*"
    Write-Host "`nGenerated files:" -ForegroundColor Cyan
    $generatedFiles | ForEach-Object {
        Write-Host "   - $($_.Name)" -ForegroundColor Green
    }

    # Test migration if requested
    if ($TestMigration) {
        Write-Host "`nTesting migration application..." -ForegroundColor Cyan
        Write-Host "   Connection: $ConnectionString" -ForegroundColor Gray
        
        $confirmTest = Read-Host "This will modify the test database. Continue? (y/N)"
        if ($confirmTest -eq 'y' -or $confirmTest -eq 'Y') {
            dotnet ef database update --context JellyfinDbContext --connection "$ConnectionString" --verbose
            
            if ($LASTEXITCODE -eq 0) {
                Write-Host "Migration applied successfully to test database!" -ForegroundColor Green
            } else {
                Write-Host "Migration application failed. Check the error above." -ForegroundColor Yellow
            }
        } else {
            Write-Host "Test migration skipped" -ForegroundColor Cyan
        }
    }

    Write-Host "`nMigration generation complete!" -ForegroundColor Green
    Write-Host "`nNext steps:" -ForegroundColor Cyan
    Write-Host "   1. Review the generated migration files" -ForegroundColor White
    Write-Host "   2. Build the project to ensure no compilation errors" -ForegroundColor White
    Write-Host "   3. Test with a PostgreSQL database" -ForegroundColor White
    Write-Host "   4. Commit the migration files to source control" -ForegroundColor White

} catch {
    Write-Host "`nError: $_" -ForegroundColor Red
    Write-Host $_.ScriptStackTrace -ForegroundColor Red
    exit 1
} finally {
    Pop-Location
}

Write-Host "`nDone!" -ForegroundColor Green
