# ============================================================
# DBAOps Futuristic Enterprise™ - Full Installer
# ============================================================
# USAGE:
#   .\Setup.ps1
#   .\Setup.ps1 -Silent -SQLServer "SERVER\INSTANCE" -LicenseKey "YOUR-KEY"
# ============================================================

param(
    [switch]$Silent,
    [string]$SQLServer = $null,
    [string]$LicenseKey = $null,
    [string]$InstallPath = "M:\RHOYLLE INNOVATION EMPIRE LLC\DBAOps Futuristic Enterprise",
    [ValidateSet("FuturisticREPO", "DBAOpsRepository")]
    [string]$Database = "DBAOpsRepository"
)

$ErrorActionPreference = "Stop"
$packageRoot = $PSScriptRoot
$defaultInstallPath = "M:\RHOYLLE INNOVATION EMPIRE LLC\DBAOps Futuristic Enterprise"

function Write-Header {
    Write-Host "`n============================================================" -ForegroundColor Cyan
    Write-Host "  DBAOps Futuristic Enterprise™ Setup" -ForegroundColor Cyan
    Write-Host "============================================================`n" -ForegroundColor Cyan
}

function Get-UserInput {
    param([string]$Prompt, [string]$Default = "")
    if ($Default) {
        $val = Read-Host "$Prompt [$Default]"
        return if ([string]::IsNullOrWhiteSpace($val)) { $Default } else { $val.Trim() }
    }
    return (Read-Host $Prompt).Trim()
}

# --- Gather inputs ---
if (-not $Silent) {
    Write-Header
    Write-Host "Enter installation parameters (or press Enter for defaults):`n" -ForegroundColor Yellow
    
    $SQLServer = Get-UserInput "SQL Server instance" $env:COMPUTERNAME
    $LicenseKey = Get-UserInput "License Key" "TRIAL"
    $pathInput = Get-UserInput "Install Path" $defaultInstallPath
    if ($pathInput) { $InstallPath = $pathInput }
    
    Write-Host "`nDatabase choice:" -ForegroundColor Yellow
    Write-Host "  1) FuturisticREPO (CMS source of truth)" -ForegroundColor White
    Write-Host "  2) DBAOpsRepository (legacy)" -ForegroundColor White
    $dbChoice = Read-Host "Select [1/2] (default: 2)"
    $Database = if ($dbChoice -eq "1") { "FuturisticREPO" } else { "DBAOpsRepository" }
} else {
    if (-not $SQLServer) { $SQLServer = $env:COMPUTERNAME }
    if (-not $LicenseKey) { $LicenseKey = "TRIAL" }
}

Write-Header
Write-Host "  SQL Server: $SQLServer" -ForegroundColor White
Write-Host "  Database:   $Database" -ForegroundColor White
Write-Host "  Install:   $InstallPath" -ForegroundColor White
Write-Host ""

# --- Create folders ---
$appFolders = @(
    "PowerShell", "Scripts", "Modules", "WebDashboard", "WebDashboard\data",
    "WebDashboard\api", "Config", "Documentation", "Logs", "Backups"
)
foreach ($f in $appFolders) {
    $path = Join-Path $InstallPath $f
    New-Item -Path $path -ItemType Directory -Force | Out-Null
}
Write-Host "[OK] Folders created" -ForegroundColor Green

# --- Deploy config (written after file deploy so it overrides template) ---
# --- Deploy database ---
$dbFolder = if ($Database -eq "FuturisticREPO") { "Database\FuturisticREPO" } else { "Database" }
$sqlFiles = @(
    "001_CreateDatabase.sql", "002_CreateSchemas.sql", "003_CreateTables.sql",
    "004_CreateViews.sql", "005_CreateProcedures.sql", "006_CreateFunctions.sql", "007_SeedData.sql"
)
if ($Database -eq "FuturisticREPO") {
    $sqlFiles = @("001_CreateDatabase.sql", "002_CreateSchemas.sql", "003_CreateTables.sql", "004_SeedData.sql", "005_DiscoveryProcedures.sql")
}
foreach ($name in $sqlFiles) {
    $path = Join-Path $packageRoot (Join-Path $dbFolder $name)
    if (Test-Path $path) {
        try {
            Invoke-Sqlcmd -ServerInstance $SQLServer -InputFile $path -TrustServerCertificate -QueryTimeout 300 -EA Stop
            Write-Host "[OK] $name" -ForegroundColor Green
        } catch {
            Write-Warning "Database $name : $_"
        }
    }
}

# --- Configure IIS ---
$iisSetup = Join-Path $packageRoot "IIS\Setup-IIS.ps1"
$webRoot = Join-Path $InstallPath "WebDashboard"
if (Test-Path $iisSetup) {
    try {
        & $iisSetup -WebRoot $webRoot
        Write-Host "[OK] IIS configured" -ForegroundColor Green
    } catch {
        Write-Warning "IIS: $_"
    }
}

# --- Deploy application files ---
$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 $InstallPath $map.Dst
    if (Test-Path $src) {
        robocopy $src $dst /E /NFL /NDL /NJH /NJS /NC /NS /NP | Out-Null
        Write-Host "[OK] Deployed $($map.Dst)" -ForegroundColor Green
    }
}

# --- Write config (after deploy so it overrides template) ---
$configPath = Join-Path $InstallPath "Config\DBAOps.config.json"
$config = @{
    InstallPath   = $InstallPath
    CentralServer = $SQLServer
    Database      = $Database
    Version       = "2.4.0"
    LicenseKey    = $LicenseKey
    WebDashboard  = @{ EnableSSL = $false; Port = 8080 }
    Alerting      = @{ SMTPPort = 587; SMTPServer = "smtp.yourdomain.com"; FromAddress = "dbaops@yourdomain.com" }
    Notes         = "Generated by Setup.ps1"
} | ConvertTo-Json -Depth 5
$config | Set-Content $configPath -Encoding UTF8
Write-Host "[OK] DBAOps.config.json written" -ForegroundColor Green

# --- Run Deploy-DBAOpsUltimate.ps1 -Mode FullBuild ---
$deployScript = Join-Path $packageRoot "Deploy-DBAOpsUltimate.ps1"
if (Test-Path $deployScript) {
    try {
        & $deployScript -Mode FullBuild -InstallPath $InstallPath -SqlInstance $SQLServer -TargetServer $SQLServer -SkipDatabase
        Write-Host "[OK] Full deployment completed" -ForegroundColor Green
    } catch {
        Write-Warning "Deploy: $_"
    }
}

# --- Generate initial data.json ---
$genScript = Join-Path $InstallPath "PowerShell\Get-DBAOpsDashboardData.ps1"
if (Test-Path $genScript) {
    try {
        & $genScript 2>&1 | Out-Null
        $dataPath = Join-Path $InstallPath "WebDashboard\data.json"
        if (Test-Path $dataPath) {
            Write-Host "[OK] data.json generated" -ForegroundColor Green
        }
    } catch {
        Write-Warning "data.json: $_"
    }
}

Write-Host "`n============================================================" -ForegroundColor Cyan
Write-Host "  Setup Complete - RHOYLLE INNOVATION EMPIRE LLC" -ForegroundColor Cyan
Write-Host "  Dashboard: http://$SQLServer`:8080/" -ForegroundColor White
Write-Host "  Mobile:    http://$SQLServer`:8080/mobile/" -ForegroundColor White
Write-Host "  API:      http://$SQLServer`:9002/api (run Start-DBAOpsAPI.ps1)" -ForegroundColor White
Write-Host "============================================================`n" -ForegroundColor Cyan
