# Deployment Script for Development Server
# Run this script to deploy code changes and apply database migrations

param(
    [switch]$SkipBuild,
    [switch]$SkipMigrations,
    [switch]$WhatIf
)

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Powder Coating App - Dev Deployment" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

$ErrorActionPreference = "Stop"
$projectRoot = Split-Path -Parent $PSScriptRoot
$webProject = Join-Path $projectRoot "src\PowderCoating.Web"
$infraProject = Join-Path $projectRoot "src\PowderCoating.Infrastructure"

# Step 1: Check current location
Write-Host "[1/5] Checking environment..." -ForegroundColor Yellow
if (-not (Test-Path $webProject)) {
    Write-Host "ERROR: Web project not found at $webProject" -ForegroundColor Red
    exit 1
}
Write-Host "✓ Project structure verified" -ForegroundColor Green
Write-Host ""

# Step 2: Build the solution
if (-not $SkipBuild) {
    Write-Host "[2/5] Building solution..." -ForegroundColor Yellow
    if ($WhatIf) {
        Write-Host "WHAT-IF: Would run: dotnet build --configuration Release" -ForegroundColor Gray
    } else {
        Push-Location $projectRoot
        dotnet build --configuration Release
        if ($LASTEXITCODE -ne 0) {
            Write-Host "ERROR: Build failed" -ForegroundColor Red
            Pop-Location
            exit 1
        }
        Pop-Location
        Write-Host "✓ Build successful" -ForegroundColor Green
    }
} else {
    Write-Host "[2/5] Skipping build (--SkipBuild specified)" -ForegroundColor Gray
}
Write-Host ""

# Step 3: Check for pending migrations
Write-Host "[3/5] Checking database migrations..." -ForegroundColor Yellow
if ($WhatIf) {
    Write-Host "WHAT-IF: Would check migrations with: dotnet ef migrations list" -ForegroundColor Gray
} else {
    Push-Location $webProject

    # List all migrations
    Write-Host "Listing all migrations:" -ForegroundColor Cyan
    dotnet ef migrations list --project $infraProject --no-build

    Pop-Location
}
Write-Host ""

# Step 4: Apply migrations
if (-not $SkipMigrations) {
    Write-Host "[4/5] Applying database migrations..." -ForegroundColor Yellow

    if ($WhatIf) {
        Write-Host "WHAT-IF: Would run: dotnet ef database update" -ForegroundColor Gray
    } else {
        $confirm = Read-Host "Apply migrations to database? (y/N)"
        if ($confirm -eq 'y' -or $confirm -eq 'Y') {
            Push-Location $webProject

            dotnet ef database update --project $infraProject --no-build
            if ($LASTEXITCODE -ne 0) {
                Write-Host "ERROR: Migration failed" -ForegroundColor Red
                Pop-Location
                exit 1
            }

            Pop-Location
            Write-Host "✓ Migrations applied successfully" -ForegroundColor Green
        } else {
            Write-Host "⊘ Migrations skipped by user" -ForegroundColor Yellow
        }
    }
} else {
    Write-Host "[4/5] Skipping migrations (--SkipMigrations specified)" -ForegroundColor Gray
}
Write-Host ""

# Step 5: Summary
Write-Host "[5/5] Deployment Summary" -ForegroundColor Yellow
Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Gray
Write-Host "Recent Changes Deployed:" -ForegroundColor Cyan
Write-Host "  • Security Headers Added (CSP, HSTS, X-Frame-Options)" -ForegroundColor White
Write-Host "  • Password Policy Strengthened (12 chars, special chars required)" -ForegroundColor White
Write-Host "  • CORS Policy Restricted (config-based whitelist)" -ForegroundColor White
Write-Host "  • Path Traversal Protection Enhanced" -ForegroundColor White
Write-Host "  • IDOR Protection on Profile Photos" -ForegroundColor White
Write-Host "  • Session Cookies Hardened (Secure, SameSite=Strict)" -ForegroundColor White
Write-Host "  • JWT Expiration Reduced (15 minutes)" -ForegroundColor White
Write-Host "  • File Upload Names Use GUIDs" -ForegroundColor White
Write-Host "  • Input Validation (SecurityHelper class)" -ForegroundColor White
Write-Host "  • AppConstants.Policies Updated (CompanyAdminOnly added)" -ForegroundColor White
Write-Host ""
Write-Host "Configuration Files:" -ForegroundColor Cyan
Write-Host "  ✓ appsettings.Development.json - Dev configuration active" -ForegroundColor Green
Write-Host "  ✓ appsettings.json - Production placeholders only" -ForegroundColor Green
Write-Host ""
Write-Host "Security Documentation:" -ForegroundColor Cyan
Write-Host "  → SECURITY_FIXES_SUMMARY.md - Complete fix list" -ForegroundColor White
Write-Host "  → DEPLOYMENT_CONFIGURATION.md - Production deployment guide" -ForegroundColor White
Write-Host ""

if (-not $WhatIf) {
    Write-Host "✓ DEPLOYMENT COMPLETE" -ForegroundColor Green
} else {
    Write-Host "⊘ WHAT-IF MODE - No changes made" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "Next Steps:" -ForegroundColor Cyan
Write-Host "  1. Test the application: https://localhost:58461" -ForegroundColor White
Write-Host "  2. Verify Data Lookups tab loads without CSP errors" -ForegroundColor White
Write-Host "  3. Test password policy (12 chars, special char required)" -ForegroundColor White
Write-Host "  4. Review SECURITY_FIXES_SUMMARY.md for all changes" -ForegroundColor White
Write-Host ""
Write-Host "Rollback (if needed):" -ForegroundColor Yellow
Write-Host "  git log --oneline  # Find commit hash before deployment" -ForegroundColor Gray
Write-Host "  git reset --hard <commit-hash>" -ForegroundColor Gray
Write-Host "  dotnet ef database update <migration-name> --project src/PowderCoating.Infrastructure" -ForegroundColor Gray
Write-Host ""
