# Central Data Gateway API Installer
# Run this script as Administrator
#Requires -RunAsAdministrator

param(
    [string]$SourcePath = (Join-Path $PSScriptRoot | Resolve-Path).Path
)

# Configuration
$AppName = "BC Edelivery API"
$Version = "1.0.0"
$Publisher = "Økonomistyrelsen"
$InstallPath = "$env:ProgramFiles\$Publisher\$AppName"
$IconPath = "\oes_logo_small3_ESr_icon.ico"
$RegPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$AppName"
$RegPathWow = "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$AppName"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host " $AppName Installer" -ForegroundColor Cyan
Write-Host " Version: $Version" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Validate source path
if (-not (Test-Path $SourcePath)) {
    Write-Host "ERROR: Source path '$SourcePath' not found!" -ForegroundColor Red
    Write-Host "Please specify the correct path using -SourcePath parameter" -ForegroundColor Yellow
    exit 1
}

# Check if already installed and compare versions
if (Test-Path $InstallPath) {
    Write-Host "WARNING: Installation directory already exists: $InstallPath" -ForegroundColor Yellow
    
    # Get installed version from registry (check both locations)
    $InstalledVersion = "Unknown"
    $RegPathToCheck = $null
    
    if (Test-Path $RegPath) {
        $RegPathToCheck = $RegPath
    } elseif (Test-Path $RegPathWow) {
        $RegPathToCheck = $RegPathWow
    }
    
    if ($RegPathToCheck) {
        $InstalledVersion = (Get-ItemProperty -Path $RegPathToCheck -Name "DisplayVersion" -ErrorAction SilentlyContinue).DisplayVersion
        if ($InstalledVersion) {
            Write-Host "Currently installed version: $InstalledVersion" -ForegroundColor Yellow
            Write-Host "New version to install: $Version" -ForegroundColor Yellow
            Write-Host ""
            
            # Compare versions
            try {
                $currentVer = [Version]$InstalledVersion
                $newVer = [Version]$Version
                
                if ($newVer -lt $currentVer) {
                    Write-Host "ERROR: Cannot downgrade from version $InstalledVersion to $Version" -ForegroundColor Red
                    Write-Host "For rollback, please uninstall the current version first, then install the older version." -ForegroundColor Yellow
                    Write-Host ""
                    Write-Host "To uninstall, run:" -ForegroundColor Cyan
                    Write-Host "  powershell.exe -ExecutionPolicy Bypass -File `"$InstallPath\Uninstall.ps1`"" -ForegroundColor White
                    Write-Host "Or use 'Add or Remove Programs' in Windows Settings." -ForegroundColor White
                    exit 1
                }
                elseif ($newVer -eq $currentVer) {
                    Write-Host "Same version detected. This will reinstall version $Version." -ForegroundColor Yellow
                }
                else {
                    Write-Host "Upgrading from version $InstalledVersion to $Version." -ForegroundColor Green
                }
            }
            catch {
                Write-Host "WARNING: Could not compare versions. Proceeding with caution." -ForegroundColor Yellow
            }
        }
    }
    
    $response = Read-Host "Do you want to continue? (Y/N)"
    if ($response -ne 'Y') {
        Write-Host "Installation cancelled." -ForegroundColor Yellow
        exit 0
    }
    
    Write-Host "Removing existing installation..." -ForegroundColor Yellow
    Remove-Item -Path $InstallPath -Recurse -Force
}

try {
    # Create installation directory
    Write-Host "Creating installation directory..." -ForegroundColor Green
    New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null

    # Copy files
    Write-Host "Copying files to $InstallPath..." -ForegroundColor Green
    Copy-Item -Path "$SourcePath\*" -Destination $InstallPath -Recurse -Force

    # Copy icon file if provided
    $FinalIconPath = ""
    if ($IconPath -and (Test-Path $IconPath)) {
        Write-Host "Copying icon file..." -ForegroundColor Green
        $IconFileName = Split-Path $IconPath -Leaf
        Copy-Item -Path $IconPath -Destination "$InstallPath\$IconFileName" -Force
        $FinalIconPath = "$InstallPath\$IconFileName"
    }
    elseif (Test-Path "$SourcePath\app.ico") {
        # Check if icon exists in source path
        $FinalIconPath = "$InstallPath\app.ico"
    }

    # Calculate installation size
    $Size = (Get-ChildItem -Path $InstallPath -Recurse | Measure-Object -Property Length -Sum).Sum
    $SizeKB = [math]::Round($Size / 1KB, 2)

    # Register in Windows Registry (Add/Remove Programs)
    Write-Host "Registering application in Windows Registry..." -ForegroundColor Green
    if (-not (Test-Path $RegPath)) {
        New-Item -Path $RegPath -Force | Out-Null
    }

    # Set registry values
    Set-ItemProperty -Path $RegPath -Name "DisplayName" -Value $AppName
    Set-ItemProperty -Path $RegPath -Name "DisplayVersion" -Value $Version
    Set-ItemProperty -Path $RegPath -Name "Publisher" -Value $Publisher
    Set-ItemProperty -Path $RegPath -Name "InstallLocation" -Value $InstallPath
    Set-ItemProperty -Path $RegPath -Name "InstallDate" -Value (Get-Date -Format "yyyyMMdd")
    Set-ItemProperty -Path $RegPath -Name "EstimatedSize" -Value ([int]$SizeKB) -Type DWord
    Set-ItemProperty -Path $RegPath -Name "NoModify" -Value 1 -Type DWord
    Set-ItemProperty -Path $RegPath -Name "NoRepair" -Value 1 -Type DWord
    Set-ItemProperty -Path $RegPath -Name "UninstallString" -Value "powershell.exe -ExecutionPolicy Bypass -File `"$InstallPath\Uninstall.ps1`""
    Set-ItemProperty -Path $RegPath -Name "URLInfoAbout" -Value "https://yourcompany.com"
    Set-ItemProperty -Path $RegPath -Name "HelpLink" -Value "https://yourcompany.com/support"

    # Set icon if available
    if ($FinalIconPath) {
        Set-ItemProperty -Path $RegPath -Name "DisplayIcon" -Value $FinalIconPath
        Write-Host "Icon registered: $FinalIconPath" -ForegroundColor Green
    }

    # Create uninstaller script - FIXED VERSION
    Write-Host "Creating uninstaller script..." -ForegroundColor Green
    $UninstallScript = @"
#Requires -RunAsAdministrator

Write-Host "Uninstalling $AppName..." -ForegroundColor Yellow
Write-Host ""

# Remove registry entry FIRST (before deleting files)
if (Test-Path "$RegPath") {
    Write-Host "Removing registry entry..." -ForegroundColor Green
    Remove-Item -Path "$RegPath" -Force
    Write-Host "Registry entry removed successfully." -ForegroundColor Green
}

# Remove installation directory (this script will be deleted too)
if (Test-Path "$InstallPath") {
    Write-Host "Removing files from $InstallPath..." -ForegroundColor Green
    
    # Use cmd to schedule deletion after script exits
    `$cmd = "cmd.exe"
    `$args = "/c timeout /t 2 /nobreak > nul && rmdir /S /Q ```"$InstallPath```""
    
    Write-Host "Files will be removed momentarily..." -ForegroundColor Green
    
    # Start cmd in hidden window and exit immediately
    Start-Process -FilePath `$cmd -ArgumentList `$args -WindowStyle Hidden
    
    Write-Host ""
    Write-Host "$AppName has been uninstalled successfully." -ForegroundColor Green
    Write-Host "Press any key to exit..." -ForegroundColor Yellow
    `$null = `$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 0
}
else {
    Write-Host "Installation directory not found." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "$AppName has been uninstalled successfully." -ForegroundColor Green
Write-Host "Press any key to exit..." -ForegroundColor Yellow
`$null = `$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
"@

    Set-Content -Path "$InstallPath\Uninstall.ps1" -Value $UninstallScript -Force

    # Create a README file
    $ReadmeContent = @"
$AppName - Version $Version

Installed: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Installation Directory: $InstallPath

USAGE:
------
These files are ready to be copied to one or more IIS website directories.

To deploy to an IIS website:
1. Copy all files from this directory to your IIS website root
2. Configure the website's application pool (recommended: No Managed Code for .NET Core)
3. Ensure the application pool identity has read access to these files
4. Configure appsettings.json as needed for your environment

UNINSTALL:
----------
To uninstall, run as Administrator:
powershell.exe -ExecutionPolicy Bypass -File "$InstallPath\Uninstall.ps1"

Or use "Add or Remove Programs" in Windows Settings.
"@

    Set-Content -Path "$InstallPath\README.txt" -Value $ReadmeContent -Force

    Write-Host ""
    Write-Host "========================================" -ForegroundColor Green
    Write-Host " Installation Completed Successfully!" -ForegroundColor Green
    Write-Host "========================================" -ForegroundColor Green
    Write-Host ""
    Write-Host "Installation Details:" -ForegroundColor Cyan
    Write-Host "  - Location: $InstallPath" -ForegroundColor White
    Write-Host "  - Version: $Version" -ForegroundColor White
    Write-Host "  - Size: $SizeKB KB" -ForegroundColor White
    Write-Host ""
    Write-Host "Next Steps:" -ForegroundColor Cyan
    Write-Host "  1. Copy files from '$InstallPath' to your IIS website(s)" -ForegroundColor White
    Write-Host "  2. Configure IIS application pool for .NET Core" -ForegroundColor White
    Write-Host "  3. Update appsettings.json for each environment" -ForegroundColor White
    Write-Host ""
    Write-Host "The application is now registered in Add/Remove Programs." -ForegroundColor Yellow
    Write-Host ""
}
catch {
    Write-Host ""
    Write-Host "ERROR: Installation failed!" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    
    # Cleanup on failure
    if (Test-Path $InstallPath) {
        Write-Host "Cleaning up..." -ForegroundColor Yellow
        Remove-Item -Path $InstallPath -Recurse -Force -ErrorAction SilentlyContinue
    }
    if (Test-Path $RegPath) {
        Remove-Item -Path $RegPath -Force -ErrorAction SilentlyContinue
    }
    
    exit 1
}