#!/usr/bin/env pwsh
# ColaFlow Development Environment Stop Script
# This script stops both backend API and frontend web application

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Stopping ColaFlow Services" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Stop backend (dotnet processes)
Write-Host "[Backend] Stopping all .NET processes..." -ForegroundColor Yellow
try {
    $dotnetProcesses = Get-Process -Name "dotnet" -ErrorAction SilentlyContinue
    if ($dotnetProcesses) {
        $dotnetProcesses | Stop-Process -Force
        Write-Host "[Backend] Stopped $($dotnetProcesses.Count) dotnet process(es)" -ForegroundColor Green
    } else {
        Write-Host "[Backend] No dotnet processes found" -ForegroundColor Gray
    }
} catch {
    Write-Host "[Backend] Error stopping dotnet processes: $_" -ForegroundColor Red
}

# Stop frontend (node processes on port 3000)
Write-Host "[Frontend] Stopping Node.js processes on port 3000..." -ForegroundColor Yellow
try {
    $port = 3000
    $connections = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue
    if ($connections) {
        $pids = $connections | Select-Object -ExpandProperty OwningProcess -Unique
        foreach ($pid in $pids) {
            Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue
            Write-Host "[Frontend] Stopped process $pid" -ForegroundColor Green
        }
    } else {
        Write-Host "[Frontend] No processes found on port 3000" -ForegroundColor Gray
    }
} catch {
    Write-Host "[Frontend] Error stopping frontend processes: $_" -ForegroundColor Red
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Services Stopped" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
