[CmdletBinding()]
param(
    [string]$InstallDir = (Join-Path $env:LOCALAPPDATA "Programs\RozHider"),
    [switch]$NoDesktopShortcut
)

$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$AppName = "RozHider"
$AppVersion = "1.0.0"
$Runtime = "win-x64"
$PackageDir = Join-Path $PSScriptRoot "app"
$LocalDotnetDir = Join-Path $PSScriptRoot ".dotnet"
$TemporaryPublishDir = Join-Path ([System.IO.Path]::GetTempPath()) "RozHider-publish"
$UninstallRegistryPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\RozHider"

function Write-Step {
    param([string]$Message)

    Write-Host "==> $Message" -ForegroundColor Cyan
}

function Get-DotnetCommand {
    $dotnetCommand = Get-Command dotnet -ErrorAction SilentlyContinue
    if ($dotnetCommand) {
        return $dotnetCommand.Source
    }

    $localDotnetExe = Join-Path $LocalDotnetDir "dotnet.exe"
    if (Test-Path $localDotnetExe) {
        return $localDotnetExe
    }

    Write-Step ".NET 8 SDK bulunamadi. Yerel kopya indiriliyor."
    $installerPath = Join-Path ([System.IO.Path]::GetTempPath()) "dotnet-install.ps1"
    Invoke-WebRequest -Uri "https://dot.net/v1/dotnet-install.ps1" -OutFile $installerPath
    & powershell -NoProfile -ExecutionPolicy Bypass -File $installerPath -Channel "8.0" -InstallDir $LocalDotnetDir -NoPath | Out-Host

    if ($LASTEXITCODE -ne 0 -or -not (Test-Path $localDotnetExe)) {
        throw ".NET 8 SDK indirilemedi."
    }

    return $localDotnetExe
}

function Publish-FromSource {
    param(
        [string]$DotnetExe,
        [string]$OutputDir
    )

    $projectPath = Join-Path $PSScriptRoot "RozHider\RozHider.csproj"
    if (-not (Test-Path $projectPath)) {
        throw "Kaynak proje bulunamadi: $projectPath"
    }

    if (Test-Path $OutputDir) {
        Remove-Item -Path $OutputDir -Recurse -Force
    }

    Write-Step "RozHider kaynak koddan yayinlaniyor."
    & $DotnetExe publish $projectPath `
        -c Release `
        -r $Runtime `
        --self-contained true `
        -p:PublishSingleFile=true `
        -p:IncludeNativeLibrariesForSelfExtract=true `
        -p:EnableCompressionInSingleFile=true `
        -o $OutputDir | Out-Host

    if ($LASTEXITCODE -ne 0) {
        throw "dotnet publish basarisiz oldu."
    }
}

function Resolve-AppSource {
    $packagedExe = Join-Path $PackageDir "$AppName.exe"
    if (Test-Path $packagedExe) {
        Write-Step "Hazir paket bulundu."
        return $PackageDir
    }

    $dotnetExe = Get-DotnetCommand
    Publish-FromSource -DotnetExe $dotnetExe -OutputDir $TemporaryPublishDir
    return $TemporaryPublishDir
}

function Install-AppFiles {
    param([string]$SourceDir)

    Write-Step "Dosyalar kopyalaniyor: $InstallDir"
    New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null

    Get-ChildItem -Path $InstallDir -Force -ErrorAction SilentlyContinue | ForEach-Object {
        Remove-Item -Path $_.FullName -Recurse -Force
    }

    Copy-Item -Path (Join-Path $SourceDir "*") -Destination $InstallDir -Recurse -Force
}

function New-Shortcut {
    param(
        [string]$ShortcutPath,
        [string]$TargetPath,
        [string]$Description
    )

    $shell = New-Object -ComObject WScript.Shell
    $shortcut = $shell.CreateShortcut($ShortcutPath)
    $shortcut.TargetPath = $TargetPath
    $shortcut.WorkingDirectory = Split-Path -Parent $TargetPath
    $shortcut.IconLocation = "$TargetPath,0"
    $shortcut.Description = $Description
    $shortcut.Save()
}

function Write-UninstallScript {
    param([string]$TargetInstallDir)

    $desktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "$AppName.lnk"
    $startMenuShortcut = Join-Path ([Environment]::GetFolderPath("Programs")) "$AppName.lnk"
    $uninstallScriptPath = Join-Path $TargetInstallDir "Uninstall-RozHider.ps1"

    $uninstallScript = @"
`$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

`$installDir = '$TargetInstallDir'
`$desktopShortcut = '$desktopShortcut'
`$startMenuShortcut = '$startMenuShortcut'
`$registryPath = '$UninstallRegistryPath'

if (Test-Path `$desktopShortcut) {
    Remove-Item `$desktopShortcut -Force
}

if (Test-Path `$startMenuShortcut) {
    Remove-Item `$startMenuShortcut -Force
}

if (Test-Path `$registryPath) {
    Remove-Item `$registryPath -Recurse -Force
}

if (Test-Path `$installDir) {
    Remove-Item `$installDir -Recurse -Force
}
"@

    Set-Content -Path $uninstallScriptPath -Value $uninstallScript -Encoding ASCII
    return $uninstallScriptPath
}

function Register-UninstallEntry {
    param(
        [string]$TargetInstallDir,
        [string]$ExePath,
        [string]$UninstallScriptPath
    )

    Write-Step "Kaldirma kaydi ekleniyor."
    New-Item -Path $UninstallRegistryPath -Force | Out-Null
    Set-ItemProperty -Path $UninstallRegistryPath -Name "DisplayName" -Value $AppName
    Set-ItemProperty -Path $UninstallRegistryPath -Name "DisplayVersion" -Value $AppVersion
    Set-ItemProperty -Path $UninstallRegistryPath -Name "Publisher" -Value $AppName
    Set-ItemProperty -Path $UninstallRegistryPath -Name "InstallLocation" -Value $TargetInstallDir
    Set-ItemProperty -Path $UninstallRegistryPath -Name "DisplayIcon" -Value $ExePath
    Set-ItemProperty -Path $UninstallRegistryPath -Name "UninstallString" -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$UninstallScriptPath`""
    Set-ItemProperty -Path $UninstallRegistryPath -Name "NoModify" -Value 1 -Type DWord
    Set-ItemProperty -Path $UninstallRegistryPath -Name "NoRepair" -Value 1 -Type DWord
}

function Create-Shortcuts {
    param([string]$ExePath)

    Write-Step "Kisayollar olusturuluyor."
    $desktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "$AppName.lnk"
    $startMenuShortcut = Join-Path ([Environment]::GetFolderPath("Programs")) "$AppName.lnk"

    New-Shortcut -ShortcutPath $startMenuShortcut -TargetPath $ExePath -Description $AppName

    if (-not $NoDesktopShortcut) {
        New-Shortcut -ShortcutPath $desktopShortcut -TargetPath $ExePath -Description $AppName
    }
}

if (-not [Environment]::Is64BitOperatingSystem) {
    throw "RozHider yalnizca 64-bit Windows uzerinde desteklenir."
}

$sourceDir = Resolve-AppSource
Install-AppFiles -SourceDir $sourceDir

$installedExe = Join-Path $InstallDir "$AppName.exe"
if (-not (Test-Path $installedExe)) {
    throw "Kurulum tamamlanamadi. Calistirilabilir dosya bulunamadi: $installedExe"
}

$uninstallScriptPath = Write-UninstallScript -TargetInstallDir $InstallDir
Register-UninstallEntry -TargetInstallDir $InstallDir -ExePath $installedExe -UninstallScriptPath $uninstallScriptPath
Create-Shortcuts -ExePath $installedExe

Write-Host ""
Write-Host "$AppName kurulumu tamamlandi." -ForegroundColor Green
Write-Host "Konum: $InstallDir"
