# ============================================================================
# 03 — Setup 3 IIS sites: DYD.Api / DYD.User / DYD.Admin
# Run as Administrator on VPS after 01-install-prerequisites.ps1
# ============================================================================

#Requires -RunAsAdministrator

$ErrorActionPreference = 'Stop'
Import-Module WebAdministration -ErrorAction Stop

# --- CONFIG ------------------------------------------------------------------
$BaseDir   = 'C:\inetpub'
$Sites = @(
    @{
        Name      = 'DYD.Api'
        AppPool   = 'DYD.ApiPool'
        Path      = "$BaseDir\DYD.Api"
        HttpPort  = 5443
        HttpsPort = 443
        Host      = 'api.ski-ump.com.vn'
        LogsPath  = "$BaseDir\DYD.Api\logs"
        Managed   = $true      # .NET Core → No Managed Code
    },
    @{
        Name      = 'DYD.User'
        AppPool   = ''          # static site, no app pool
        Path      = "$BaseDir\DYD.User"
        HttpPort  = 8080
        HttpsPort = 443
        Host      = 'ski-ump.com.vn'
        Managed   = $false
    },
    @{
        Name      = 'DYD.Admin'
        AppPool   = ''
        Path      = "$BaseDir\DYD.Admin"
        HttpPort  = 8082
        HttpsPort = 443
        Host      = 'admin.ski-ump.com.vn'
        Managed   = $false
    }
)

# --- HELPER ------------------------------------------------------------------
function New-Dir($p) {
    if (-not (Test-Path $p)) {
        New-Item -ItemType Directory -Path $p -Force | Out-Null
        Write-Host "  Created: $p" -ForegroundColor Green
    }
}

function New-ApiAppPool($name) {
    if (Test-Path "IIS:\AppPools\$name") {
        Write-Host "  [OK] AppPool $name exists" -ForegroundColor Green
        return
    }
    New-WebAppPool -Name $name | Out-Null
    Set-ItemProperty "IIS:\AppPools\$name" -name managedRuntimeVersion -value ''
    Set-ItemProperty "IIS:\AppPools\$name" -name startMode -value 'AlwaysRunning'
    Set-ItemProperty "IIS:\AppPools\$name" -name processModel.idleTimeout -value ([TimeSpan]::Zero)
    Write-Host "  Created AppPool: $name (No Managed Code, AlwaysRunning)" -ForegroundColor Green
}

# --- DIRECTORIES -------------------------------------------------------------
Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "  1/4 — Create directories" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
foreach ($s in $Sites) {
    New-Dir $s.Path
    if ($s.LogsPath) { New-Dir $s.LogsPath }
}
New-Dir "$BaseDir\backups"

# --- APP POOLS ---------------------------------------------------------------
Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "  2/4 — Create App Pools" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
foreach ($s in $Sites) {
    if ($s.Managed -and $s.AppPool) {
        New-ApiAppPool $s.AppPool
    }
}

# --- SITES -------------------------------------------------------------------
Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "  3/4 — Create Sites + Bindings" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
foreach ($s in $Sites) {
    # Remove existing site if port conflict
    $existing = Get-Website -Name $s.Name -ErrorAction SilentlyContinue
    if ($existing) {
        Write-Host "  Site $($s.Name) exists. Skipping creation." -ForegroundColor Yellow
        continue
    }

    if ($s.Managed) {
        New-Website -Name $s.Name `
            -PhysicalPath $s.Path `
            -ApplicationPool $s.AppPool `
            -Port $s.HttpPort `
            -HostHeader $s.Host `
            -Force | Out-Null
    }
    else {
        New-Website -Name $s.Name `
            -PhysicalPath $s.Path `
            -Port $s.HttpPort `
            -HostHeader $s.Host `
            -Force | Out-Null
    }
    Write-Host "  Created site: $($s.Name) on :$($s.HttpPort) — host: $($s.Host)" -ForegroundColor Green
}

# --- PLACEHOLDER INDEX -------------------------------------------------------
Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "  4/4 — Placeholder index.html" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
foreach ($s in $Sites) {
    $indexPath = Join-Path $s.Path 'index.html'
    if (-not (Test-Path $indexPath)) {
        @"
<!DOCTYPE html>
<html><head><title>$($s.Name)</title></head>
<body><h1>$($s.Name) — placeholder</h1>
<p>Site chưa được deploy. Chạy pipeline hoặc deploy thủ công.</p></body></html>
"@ | Set-Content $indexPath -Encoding UTF8
    }
}

# --- FIREWALL ----------------------------------------------------------------
Write-Host ""
Write-Host "Firewall rules (HTTP 80, HTTPS 443, custom ports):" -ForegroundColor Cyan
$ports = @(80, 443, 5443, 8080, 8082, 3000)  # 3000 cho Gitea sau
foreach ($p in $ports) {
    $rule = "DYD-TCP-$p"
    if (-not (Get-NetFirewallRule -DisplayName $rule -ErrorAction SilentlyContinue)) {
        New-NetFirewallRule -DisplayName $rule -Direction Inbound -Protocol TCP -LocalPort $p -Action Allow | Out-Null
        Write-Host "  [+] TCP $p allowed" -ForegroundColor Green
    }
}

# --- SUMMARY -----------------------------------------------------------------
Write-Host ""
Write-Host "=========================================================" -ForegroundColor Green
Write-Host " DONE — 3 IIS sites ready" -ForegroundColor Green
Write-Host "=========================================================" -ForegroundColor Green
Write-Host ""
Get-Website | Where-Object { $_.Name -like 'DYD.*' } | Format-Table -AutoSize Name, State, PhysicalPath, @{L='Bindings';E={($_.Bindings.Collection.bindingInformation) -join ', '}}

Write-Host "HTTP URLs (cần bind host file hoặc DNS):"
foreach ($s in $Sites) {
    Write-Host "  http://$($s.Host):$($s.HttpPort)" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "Next: 04-install-gitea.ps1 + 05-setup-ssl.ps1 (sau khi DNS trỏ IP)"
