param(
    [Parameter(Mandatory=$true)]
    [string]$Name,
    [int]$Port = 0
)

$clean = $Name.Trim()
if (-not $clean) { throw "Name is required." }

# Normalize name for Docker resources
$slug = ($clean -replace '[^a-zA-Z0-9_-]', '_').ToLower()

if ($Port -eq 0) {
    # Auto-pick port: 10001 + current compose count (simple heuristic)
    $existing = Get-ChildItem -Filter 'docker-compose-*.yml' | Measure-Object | Select-Object -ExpandProperty Count
    $Port = 10001 + $existing + 1
}

$filename = "docker-compose-$slug.yml"

$yml = @"
version: "3.8"
services:
  db:
    image: postgres:15
    container_name: odoo_${slug}_db
    environment:
      POSTGRES_DB: postgres
      POSTGRES_USER: odoo
      POSTGRES_PASSWORD: odoo
    volumes:
      - ${slug}_pgdata:/var/lib/postgresql/data
    restart: always

  odoo:
    image: odoo:17.0
    container_name: odoo_${slug}
    depends_on:
      - db
    ports:
      - "${Port}:8069"
    environment:
      HOST: db
      USER: odoo
      PASSWORD: odoo
    volumes:
      - ${slug}_odoo_data:/var/lib/odoo
      - ./addons:/mnt/extra-addons
    restart: always

volumes:
  ${slug}_pgdata:
  ${slug}_odoo_data:
"@

$yml | Set-Content -Path $filename

Write-Host "Created $filename with Odoo port $Port" -ForegroundColor Green
Write-Host "Run: docker-compose -p $slug -f $filename up -d" -ForegroundColor Cyan
