# Manage-Containers.ps1
param (
    [Parameter(Mandatory=$true)]
    [ValidateSet('run', 'stop', 'remove')]
    [string]$Action,
    [switch]$Force
)

$ErrorActionPreference = "Stop"

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

function Start-Container {
    Write-Host "Starting container '$containerName'..." -ForegroundColor Yellow
    
    # Check if container exists and is stopped
    $existingContainer = docker ps -a --filter "name=$containerName" --format "{{.Names}}"
    if ($existingContainer) {
        Write-Host "Container already exists, starting it..." -ForegroundColor Yellow
        docker start $containerName
    } else {
        # Run new container
        Write-Host "Creating and starting new container..." -ForegroundColor Yellow
        docker run -d -p 1433:1433 --name $containerName $imageName
    }

    if ($LASTEXITCODE -eq 0) {
        Write-Host "Container started successfully!" -ForegroundColor Green
    } else {
        Write-Host "Failed to start container" -ForegroundColor Red
        exit 1
    }
}

function Stop-Container {
    Write-Host "Stopping container '$containerName'..." -ForegroundColor Yellow
    
    # Check if container exists and is running
    $runningContainer = docker ps --filter "name=$containerName" --format "{{.Names}}"
    if ($runningContainer) {
        docker stop $containerName
        if ($LASTEXITCODE -eq 0) {
            Write-Host "Container stopped successfully!" -ForegroundColor Green
        } else {
            Write-Host "Failed to stop container" -ForegroundColor Red
            exit 1
        }
    } else {
        Write-Host "Container is not running" -ForegroundColor Yellow
    }
}

function Remove-Container {
    Write-Host "Removing container '$containerName'..." -ForegroundColor Yellow
    
    # Stop container if running
    $runningContainer = docker ps --filter "name=$containerName" --format "{{.Names}}"
    if ($runningContainer) {
        Write-Host "Stopping container first..." -ForegroundColor Yellow
        docker stop $containerName
    }

    # Remove container
    $existingContainer = docker ps -a --filter "name=$containerName" --format "{{.Names}}"
    if ($existingContainer) {
        docker rm $containerName
        if ($LASTEXITCODE -eq 0) {
            Write-Host "Container removed successfully!" -ForegroundColor Green
        } else {
            Write-Host "Failed to remove container" -ForegroundColor Red
            exit 1
        }
    } else {
        Write-Host "Container does not exist" -ForegroundColor Yellow
    }
}

try {
    switch ($Action) {
        'run' { Start-Container }
        'stop' { Stop-Container }
        'remove' { Remove-Container }
    }
} catch {
    Write-Host "An error occurred: $_" -ForegroundColor Red
    exit 1
}