# Requires -RunAsAdministrator

function Write-Status($Message, $Type = "Info") {
    switch ($Type) {
        "Info" { $Color = "White" }
        "Success" { $Color = "Green" }
        "Error" { $Color = "Red" }
        "Warning" { $Color = "Yellow" }
    }
    Write-Host ">>> $Message" -ForegroundColor $Color
}

# Check if running as Administrator
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Status "This script must be run as Administrator" "Error"
    Exit 1
}

try {
    # Install Windows features required for Docker
    Write-Status "Installing required Windows features..." "Info"
    Enable-WindowsOptionalFeature -Online -FeatureName containers -All -NoRestart
    
    # Download Docker Engine
    Write-Status "Downloading Docker Engine..." "Info"
    $dockerUrl = "https://download.docker.com/win/static/stable/x86_64/docker-24.0.7.zip"
    $dockerZip = "$env:TEMP\docker.zip"
    $dockerPath = "C:\Program Files\Docker"
    
    Invoke-WebRequest -Uri $dockerUrl -OutFile $dockerZip
    
    # Extract Docker Engine
    Write-Status "Extracting Docker Engine..." "Info"
    Expand-Archive -Path $dockerZip -DestinationPath $env:ProgramFiles -Force
    Remove-Item $dockerZip -Force
    
    # Add Docker to PATH
    Write-Status "Adding Docker to PATH..." "Info"
    $oldPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine)
    if (-not $oldPath.Contains($dockerPath)) {
        $newPath = "$oldPath;$dockerPath"
        [Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::Machine)
    }
    
    # Create Docker service
    Write-Status "Creating Docker service..." "Info"
    & "$dockerPath\dockerd.exe" --register-service
    
    # Start Docker service
    Write-Status "Starting Docker service..." "Info"
    Start-Service docker
    
    # Test Docker installation
    Write-Status "Testing Docker installation..." "Info"
    docker version
    if ($LASTEXITCODE -eq 0) {
        Write-Status "Docker Engine installed successfully!" "Success"
    } else {
        Write-Status "Docker installation completed but service test failed" "Warning"
    }
    
    # Pull SQL Server image
    Write-Status "Pulling SQL Server image..." "Info"
    docker pull mcr.microsoft.com/mssql/server:2022-latest
    
    Write-Status "`nDocker Engine installation completed!" "Success"
    Write-Status "You can now use Docker commands directly." "Info"
    Write-Status "Please restart your computer to ensure all changes take effect." "Warning"

} catch {
    Write-Status "An error occurred: $_" "Error"
    Exit 1
}