<#
.SYNOPSIS
    Create web.config for ROA2WEB IIS Application

.DESCRIPTION
    Creates web.config in C:\inetpub\wwwroot\roa2web\frontend\ with correct proxy settings
    for backend on localhost:8000

.EXAMPLE
    .\Create-WebConfig.ps1
#>

$ErrorActionPreference = "Stop"

$webConfigPath = "C:\inetpub\wwwroot\roa2web\frontend\web.config"

Write-Host "`n[*] Creating web.config at: $webConfigPath" -ForegroundColor Cyan

$webConfigContent = @"
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <urlCompression doStaticCompression="true" doDynamicCompression="true" />
        <defaultDocument>
            <files>
                <clear />
                <add value="index.html" />
            </files>
        </defaultDocument>
        <staticContent>
            <remove fileExtension=".json" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <remove fileExtension=".woff" />
            <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
            <remove fileExtension=".woff2" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
            <remove fileExtension=".svg" />
            <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
            <remove fileExtension=".webmanifest" />
            <mimeMap fileExtension=".webmanifest" mimeType="application/manifest+json" />
            <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
        </staticContent>
        <httpProtocol>
            <customHeaders>
                <add name="X-Frame-Options" value="DENY" />
                <add name="X-Content-Type-Options" value="nosniff" />
                <add name="X-XSS-Protection" value="1; mode=block" />
                <remove name="X-Powered-By" />
            </customHeaders>
        </httpProtocol>
        <rewrite>
            <rules>
                <rule name="API Reverse Proxy" stopProcessing="true">
                    <match url="^api/(.*)" />
                    <action type="Rewrite" url="http://localhost:8000/api/{R:1}" />
                </rule>
                <rule name="Health Check Proxy" stopProcessing="true">
                    <match url="^health$" />
                    <action type="Rewrite" url="http://localhost:8000/health" />
                </rule>
                <rule name="StaticContent" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" />
                    </conditions>
                    <action type="None" />
                </rule>
                <rule name="StaticDirectory" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" />
                    </conditions>
                    <action type="None" />
                </rule>
                <rule name="SPA Fallback" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/api" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.html" />
                </rule>
            </rules>
        </rewrite>
        <httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404" subStatusCode="-1" />
            <error statusCode="404" path="index.html" responseMode="ExecuteURL" />
        </httpErrors>
        <directoryBrowse enabled="false" />
    </system.webServer>
</configuration>
"@

try {
    # Verifică dacă directorul există
    $frontendDir = Split-Path $webConfigPath -Parent
    if (-not (Test-Path $frontendDir)) {
        Write-Host "    [ERROR] Frontend directory not found: $frontendDir" -ForegroundColor Red
        Write-Host "    Please ensure ROA2WEB is installed first." -ForegroundColor Yellow
        exit 1
    }

    # Creează web.config
    $webConfigContent | Out-File -FilePath $webConfigPath -Encoding UTF8 -Force
    Write-Host "    [OK] web.config created successfully" -ForegroundColor Green

    # Verifică conținutul
    Write-Host "`n[*] Verifying web.config..." -ForegroundColor Cyan
    if (Test-Path $webConfigPath) {
        $fileSize = (Get-Item $webConfigPath).Length
        Write-Host "    [OK] File exists, size: $fileSize bytes" -ForegroundColor Green

        # Verifică că are portul corect
        $content = Get-Content $webConfigPath -Raw
        if ($content -match "localhost:8000") {
            Write-Host "    [OK] Backend port configured: localhost:8000" -ForegroundColor Green
        } else {
            Write-Host "    [WARN] Backend port not found in config" -ForegroundColor Yellow
        }
    }

    # Verifică backend
    Write-Host "`n[*] Checking backend service..." -ForegroundColor Cyan
    $backendRunning = netstat -ano | Select-String ":8000.*LISTENING"
    if ($backendRunning) {
        Write-Host "    [OK] Backend running on port 8000" -ForegroundColor Green
    } else {
        Write-Host "    [WARN] Backend not running on port 8000" -ForegroundColor Yellow
        Write-Host "    Start backend service: Restart-Service ROA2WEB-Backend" -ForegroundColor Yellow
    }

    # Restart IIS App Pool
    Write-Host "`n[*] Restarting IIS Application Pool..." -ForegroundColor Cyan
    try {
        Restart-WebAppPool -Name "ROA2WEB-AppPool" -ErrorAction SilentlyContinue
        Write-Host "    [OK] IIS App Pool restarted" -ForegroundColor Green
    } catch {
        Write-Host "    [WARN] Could not restart app pool: $_" -ForegroundColor Yellow
        Write-Host "    Manual restart: Restart-WebAppPool -Name 'ROA2WEB-AppPool'" -ForegroundColor Yellow
    }

    Write-Host "`n" + ("=" * 70) -ForegroundColor Green
    Write-Host "  web.config CREATED SUCCESSFULLY" -ForegroundColor Green
    Write-Host ("=" * 70) -ForegroundColor Green
    Write-Host "`nNext steps:" -ForegroundColor Yellow
    Write-Host "  1. Ensure backend is running: netstat -ano | findstr 8000" -ForegroundColor Gray
    Write-Host "  2. Test health endpoint: curl http://localhost:8000/health" -ForegroundColor Gray
    Write-Host "  3. Test application: https://roa2web.romfast.ro/roa2web/" -ForegroundColor Gray
    Write-Host ""

} catch {
    Write-Host "`n    [ERROR] Failed to create web.config: $_" -ForegroundColor Red
    exit 1
}
