# ============================================================
# DBAOps Futuristic Enterprise™ - Master Deployment Script
# ONE SCRIPT TO REBUILD EVERYTHING
# ============================================================
# USAGE:
#   .\Deploy-DBAOpsUltimate.ps1 -Mode FullBuild -TargetServer NEWSQLSERVER01
#   .\Deploy-DBAOpsUltimate.ps1 -Mode Repair
#
# CANONICAL INSTALL PATH:
#   M:\RHOYLLE INNOVATION EMPIRE LLC\DBAOps Futuristic Enterprise
# ============================================================

param(
    [ValidateSet("FullBuild","Repair")]
    [string]$Mode = "Repair",
    
    [string]$TargetServer = $env:COMPUTERNAME,
    [string]$InstallPath = "M:\RHOYLLE INNOVATION EMPIRE LLC\DBAOps Futuristic Enterprise",
    [string]$TargetDrive = "M:",
    [string]$SqlInstance = $null,
    [switch]$SkipDatabase,
    [switch]$SkipIIS,
    [switch]$SkipJobs,
    [switch]$WhatIf
)

$ErrorActionPreference = "Continue"
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$packageRoot = $PSScriptRoot
$targetRoot = $InstallPath

if (-not $SqlInstance) { $SqlInstance = $TargetServer }

Write-Host "============================================================" -ForegroundColor Cyan
Write-Host "  DBAOps Futuristic Enterprise™ Deployment" -ForegroundColor Cyan
Write-Host "  Mode: $Mode" -ForegroundColor Cyan
Write-Host "  Target: $TargetServer | Install: $targetRoot" -ForegroundColor Cyan
Write-Host "  SQL: $SqlInstance" -ForegroundColor Cyan
Write-Host "  $timestamp" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan

if ($WhatIf) { Write-Host "  *** WHATIF MODE - No changes will be made ***" -ForegroundColor Yellow }

$results = @{ Success = @(); Failed = @(); Skipped = @() }

function Log-Step($step, $status, $detail) {
    $color = switch($status) { "OK" {"Green"} "FAIL" {"Red"} "SKIP" {"Yellow"} default {"Gray"} }
    Write-Host "  [$status] $step : $detail" -ForegroundColor $color
    switch($status) {
        "OK"   { $script:results.Success += "$step : $detail" }
        "FAIL" { $script:results.Failed += "$step : $detail" }
        "SKIP" { $script:results.Skipped += "$step : $detail" }
    }
}

# ============================================================
# STEP 1: Create folder structure
# ============================================================
Write-Host "`n--- Step 1: Folder Structure ---" -ForegroundColor Yellow

$appFolders = @(
    "PowerShell", "Scripts", "Modules", "WebDashboard", "WebDashboard\data",
    "WebDashboard\api", "Config", "Documentation", "Logs", "Backups"
)

if ($Mode -eq "FullBuild") {
    foreach ($f in $appFolders) {
        $path = Join-Path $targetRoot $f
        if (-not $WhatIf) { New-Item -Path $path -ItemType Directory -Force | Out-Null }
    }
    Log-Step "Folders" "OK" "$($appFolders.Count) directories created"
    
    # Also create database directories
    $dbPath = "$TargetDrive\ProdDB\DBAOps"
    if (-not $WhatIf) { New-Item -Path $dbPath -ItemType Directory -Force | Out-Null }
    Log-Step "DB Path" "OK" "$dbPath created"
} else {
    # Repair mode - just verify
    $missing = $appFolders | Where-Object { -not (Test-Path (Join-Path $targetRoot $_)) }
    if ($missing) {
        foreach ($f in $missing) {
            if (-not $WhatIf) { New-Item -Path (Join-Path $targetRoot $f) -ItemType Directory -Force | Out-Null }
        }
        Log-Step "Folders" "OK" "Restored $($missing.Count) missing folders"
    } else {
        Log-Step "Folders" "OK" "All folders intact"
    }
}

# ============================================================
# STEP 2: Deploy application files
# ============================================================
Write-Host "`n--- Step 2: Application Files ---" -ForegroundColor Yellow

$fileMaps = @(
    @{ Src = "Application\PowerShell";     Dst = "PowerShell" },
    @{ Src = "Application\Scripts";        Dst = "Scripts" },
    @{ Src = "Application\Modules";        Dst = "Modules" },
    @{ Src = "Application\WebDashboard";   Dst = "WebDashboard" },
    @{ Src = "Application\Config";         Dst = "Config" },
    @{ Src = "Application\Documentation";  Dst = "Documentation" }
)

foreach ($map in $fileMaps) {
    $src = Join-Path $packageRoot $map.Src
    $dst = Join-Path $targetRoot $map.Dst
    if (Test-Path $src) {
        if ($Mode -eq "FullBuild") {
            if (-not $WhatIf) {
                robocopy $src $dst /E /NFL /NDL /NJH /NJS /NC /NS /NP | Out-Null
            }
            $count = (Get-ChildItem $src -Recurse -File).Count
            Log-Step $map.Dst "OK" "$count files deployed"
        } else {
            # Repair mode - only copy missing or modified files
            if (-not $WhatIf) {
                robocopy $src $dst /E /XO /NFL /NDL /NJH /NJS /NC /NS /NP | Out-Null
            }
            Log-Step $map.Dst "OK" "Synced (newer files only)"
        }
    }
}

# Deploy protection scripts
$protSrc = Join-Path $packageRoot "Protection"
$protDst = Join-Path $targetRoot "Scripts"
if (Test-Path $protSrc) {
    if (-not $WhatIf) { Copy-Item "$protSrc\*" $protDst -Force -EA SilentlyContinue }
    Log-Step "Protection" "OK" "Watchdog and protection scripts deployed"
}

# ============================================================
# STEP 3: Deploy database
# ============================================================
Write-Host "`n--- Step 3: Database ---" -ForegroundColor Yellow

if ($SkipDatabase) {
    Log-Step "Database" "SKIP" "Skipped by parameter"
} else {
    $sqlFiles = @(
        "Database\001_CreateDatabase.sql",
        "Database\002_CreateSchemas.sql",
        "Database\003_CreateTables.sql",
        "Database\004_CreateViews.sql",
        "Database\005_CreateProcedures.sql",
        "Database\006_CreateFunctions.sql",
        "Database\007_SeedData.sql"
    )
    
    foreach ($sqlFile in $sqlFiles) {
        $path = Join-Path $packageRoot $sqlFile
        $name = Split-Path $sqlFile -Leaf
        if (Test-Path $path) {
            try {
                if (-not $WhatIf) {
                    Invoke-Sqlcmd -ServerInstance $SqlInstance -InputFile $path -TrustServerCertificate -QueryTimeout 300 -EA Stop
                }
                Log-Step $name "OK" "Executed successfully"
            } catch {
                Log-Step $name "FAIL" $_.Exception.Message
            }
        }
    }
}

# ============================================================
# STEP 4: Configure IIS
# ============================================================
Write-Host "`n--- Step 4: IIS Configuration ---" -ForegroundColor Yellow

if ($SkipIIS) {
    Log-Step "IIS" "SKIP" "Skipped by parameter"
} else {
    $iisSetup = Join-Path $packageRoot "IIS\Setup-IIS.ps1"
    if (Test-Path $iisSetup) {
        try {
            if (-not $WhatIf) {
                & $iisSetup -WebRoot "$targetRoot\WebDashboard"
            }
            Log-Step "IIS" "OK" "Website configured"
        } catch {
            Log-Step "IIS" "FAIL" $_.Exception.Message
        }
    }
}

# ============================================================
# STEP 5: Deploy SQL Agent jobs
# ============================================================
Write-Host "`n--- Step 5: SQL Agent Jobs ---" -ForegroundColor Yellow

if ($SkipJobs) {
    Log-Step "SQL Agent" "SKIP" "Skipped by parameter"
} else {
    $jobFile = Join-Path $packageRoot "SQLAgent\CreateAllJobs.sql"
    if (Test-Path $jobFile) {
        try {
            if (-not $WhatIf) {
                $sqlContent = Get-Content $jobFile -Raw -Encoding UTF8
                $sqlContent = $sqlContent -replace '\{\{InstallPath\}\}', $targetRoot
                $tempSql = [System.IO.Path]::GetTempFileName() + ".sql"
                $sqlContent | Set-Content $tempSql -Encoding UTF8 -NoNewline
                try {
                    Invoke-Sqlcmd -ServerInstance $SqlInstance -Database "msdb" -InputFile $tempSql -TrustServerCertificate -QueryTimeout 300 -EA Stop
                } finally {
                    Remove-Item $tempSql -Force -EA SilentlyContinue
                }
            }
            Log-Step "SQL Agent" "OK" "All jobs created (InstallPath: $targetRoot)"
        } catch {
            Log-Step "SQL Agent" "FAIL" $_.Exception.Message
        }
    }
}

# ============================================================
# STEP 6: Generate initial data and validate
# ============================================================
Write-Host "`n--- Step 6: Initialize & Validate ---" -ForegroundColor Yellow

if (-not $WhatIf) {
    # Generate data.json
    $genScript = "$targetRoot\PowerShell\Get-DBAOpsDashboardData.ps1"
    if (Test-Path $genScript) {
        try {
            & $genScript 2>&1 | Out-Null
            if ((Test-Path "$targetRoot\WebDashboard\data.json") -and (Get-Item "$targetRoot\WebDashboard\data.json").Length -gt 1000) {
                Log-Step "data.json" "OK" "$([math]::Round((Get-Item "$targetRoot\WebDashboard\data.json").Length/1KB,1)) KB generated"
            } else {
                Log-Step "data.json" "FAIL" "Generated but empty or missing"
            }
        } catch {
            Log-Step "data.json" "FAIL" $_.Exception.Message
        }
    }
    
    # Run health check
    $healthScript = "$targetRoot\Scripts\Protect-DBAOpsUltimate.ps1"
    if (Test-Path $healthScript) {
        & $healthScript -HealthCheck
    }
}

# ============================================================
# SUMMARY
# ============================================================
Write-Host "`n============================================================" -ForegroundColor Cyan
Write-Host "  DEPLOYMENT SUMMARY" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host "  Mode: $Mode" -ForegroundColor White
Write-Host "  Target: $TargetServer ($targetRoot)" -ForegroundColor White
Write-Host "  Success: $($results.Success.Count)" -ForegroundColor Green
Write-Host "  Failed:  $($results.Failed.Count)" -ForegroundColor $(if($results.Failed.Count -gt 0){'Red'}else{'Green'})
Write-Host "  Skipped: $($results.Skipped.Count)" -ForegroundColor Yellow

if ($results.Failed.Count -gt 0) {
    Write-Host "`n  FAILURES:" -ForegroundColor Red
    $results.Failed | ForEach-Object { Write-Host "    - $_" -ForegroundColor Red }
}

Write-Host "`n  Dashboard URL: http://$TargetServer`:8080/" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan