# Build-Containers.ps1
param (
    [switch]$Force
)

$ErrorActionPreference = "Stop"

function Test-WSLRequirements {
    Write-Host "Checking WSL requirements..." -ForegroundColor Yellow
    
    # Check if WSL is installed
    $wslInstalled = Get-Command wsl.exe -ErrorAction SilentlyContinue
    if (-not $wslInstalled) {
        Write-Host "WSL is not installed. Please run the following commands as Administrator:" -ForegroundColor Red
        Write-Host "wsl --install" -ForegroundColor Yellow
        Write-Host "Then restart your computer and run:" -ForegroundColor Yellow
        Write-Host "wsl --install -d Ubuntu" -ForegroundColor Yellow
        return $false
    }

    # Check if any distribution is installed
    $wslDistros = wsl --list
    if ($LASTEXITCODE -ne 0 -or $wslDistros -match "no installed distributions") {
        Write-Host "No WSL distribution found. Please run the following command as Administrator:" -ForegroundColor Red
        Write-Host "wsl --install -d Ubuntu" -ForegroundColor Yellow
        return $false
    }

    # Check if Docker Desktop is running
    $dockerPs = Get-Process "Docker Desktop" -ErrorAction SilentlyContinue
    if (-not $dockerPs) {
        Write-Host "Docker Desktop is not running. Please start Docker Desktop and try again." -ForegroundColor Red
        return $false
    }

    Write-Host "WSL requirements checked successfully!" -ForegroundColor Green
    return $true
}

# Check WSL requirements
if (-not (Test-WSLRequirements)) {
    exit 1
}

Write-Host "Starting Docker build process..." -ForegroundColor Green

# Define container names
$containerName = "st-db"
$imageName = "st-database"

# Get the current script directory
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$sqlServerPath = Join-Path $scriptPath "sql-server"

# Verify Dockerfile exists
if (-not (Test-Path (Join-Path $sqlServerPath "Dockerfile"))) {
    Write-Host "Dockerfile not found in $sqlServerPath" -ForegroundColor Red
    exit 1
}

try {
    # Change to the SQL Server directory
    Push-Location $sqlServerPath

    # Build the Docker image
    Write-Host "Building Docker image '$imageName'..." -ForegroundColor Yellow
    docker build -t $imageName .

    if ($LASTEXITCODE -eq 0) {
        Write-Host "Docker image built successfully!" -ForegroundColor Green
    } else {
        Write-Host "Failed to build Docker image" -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "An error occurred: $_" -ForegroundColor Red
    exit 1
} finally {
    # Return to original directory
    Pop-Location
}