#!/usr/bin/env bash
# EN: Generate OpenAPI spec (openapi.yaml) for a .NET microservice using dotnet swagger tofile.
#     Usage: generate-openapi.sh <service-dir> <api-project-name>
#     Example: generate-openapi.sh services/iam-service-net IamService.API
#
# VI: Tạo OpenAPI spec (openapi.yaml) cho .NET microservice dùng dotnet swagger tofile.
#     Sử dụng: generate-openapi.sh <service-dir> <api-project-name>
#     Ví dụ: generate-openapi.sh services/iam-service-net IamService.API

set -euo pipefail

SERVICE_DIR="${1:?Usage: $0 <service-dir> <api-project-name>}"
API_PROJECT="${2:?Usage: $0 <service-dir> <api-project-name>}"

CSPROJ="$SERVICE_DIR/src/$API_PROJECT/$API_PROJECT.csproj"
DLL="$SERVICE_DIR/src/$API_PROJECT/bin/Release/net10.0/$API_PROJECT.dll"
OUTPUT="$SERVICE_DIR/openapi.yaml"

echo "[generate-openapi] Service: $API_PROJECT"
echo "[generate-openapi] Output:  $OUTPUT"

# EN: Build the API project if not already built / VI: Build API project nếu chưa build
if [ ! -f "$DLL" ]; then
    echo "[generate-openapi] Building $API_PROJECT..."
    dotnet build "$CSPROJ" --configuration Release --no-restore
fi

# EN: Generate OpenAPI YAML using dotnet-swagger (Swashbuckle CLI)
# VI: Tạo OpenAPI YAML dùng dotnet-swagger (Swashbuckle CLI)
dotnet swagger tofile \
    --output "$OUTPUT" \
    --yaml \
    "$DLL" \
    v1

echo "[generate-openapi] Generated: $OUTPUT"
