#!/bin/bash

# Determine environment (default to dev)
ENVIRONMENT=${1:-dev}

if [ "$ENVIRONMENT" = "prod" ] || [ "$ENVIRONMENT" = "production" ]; then
    OPENAPI_URL="https://api.vitrown.com/api/docs/swagger.json"
else
    OPENAPI_URL="https://api.vitrown.abrino.cloud/api/docs/swagger.json"
fi

OUTPUT_DIR="./src/api/types"
GENERATOR_JAR="/usr/local/bin/openapi-generator-cli.jar"

echo "Generating API types for $ENVIRONMENT environment"
echo "Using OpenAPI URL: $OPENAPI_URL"

# Download OpenAPI schema
curl -s "$OPENAPI_URL" -o ./openapi.json

# Run generator using java directly
java -jar "$GENERATOR_JAR" generate \
  -i ./openapi.json \
  -g typescript-fetch \
  -o "$OUTPUT_DIR" \
  --skip-validate-spec \
  --additional-properties=supportsES6=true,withoutRuntimeChecks=true,modelPropertyNaming=camelCase

# Apply post-generation fix to make BASE_PATH dynamic
echo "Applying dynamic BASE_PATH fix..."
sed -i 's|export const BASE_PATH = "https://api\.vitrown\.abrino\.cloud"|import { getApiBaseUrl } from "../../../app/utils/api-config";\nexport const BASE_PATH = getApiBaseUrl()|g' src/api/types/runtime.ts
sed -i 's|export const BASE_PATH = "https://api\.vitrown\.com"|import { getApiBaseUrl } from "../../../app/utils/api-config";\nexport const BASE_PATH = getApiBaseUrl()|g' src/api/types/runtime.ts

# Clean up
rm ./openapi.json

echo "API types generated successfully with dynamic BASE_PATH"
