# PowerShell script to generate TypeScript types from OpenAPI schema

# Determine environment (default to dev)
param(
    [string]$Environment = "dev"
)

if ($Environment -eq "prod" -or $Environment -eq "production") {
    $OPENAPI_URL = "https://api.vitrown.com/api/docs/swagger.json"
} else {
    $OPENAPI_URL = "https://api.vitrown.abrino.cloud/api/docs/swagger.json"
}

$OUTPUT_DIR = "./src/api/types"
$GENERATOR_JAR = "openapi-generator-cli.jar"

# Check if Java is installed
try {
    $javaVersion = & java -version 2>&1
    Write-Host "Java is installed."
} catch {
    Write-Host "Java is not installed or not in your PATH."
    Write-Host "Please install Java from https://adoptium.net/ or https://www.oracle.com/java/technologies/downloads/"
    Write-Host "After installing Java, restart your terminal and try again."
    exit 1
}

# Check if OpenAPI Generator CLI is available
if (-not (Test-Path $GENERATOR_JAR)) {
    Write-Host "OpenAPI Generator CLI not found. Downloading..."
    Invoke-WebRequest -Uri "https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.6.0/openapi-generator-cli-6.6.0.jar" -OutFile $GENERATOR_JAR
}

Write-Host "Generating API types for $Environment environment"
Write-Host "Using OpenAPI URL: $OPENAPI_URL"

# Download OpenAPI schema
Invoke-WebRequest -Uri $OPENAPI_URL -OutFile "./openapi.json"

# Run generator using java directly
Write-Host "Generating TypeScript types..."
try {
    & 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
    Write-Host "Applying dynamic BASE_PATH fix..."
    $runtimeFile = "src/api/types/runtime.ts"
    if (Test-Path $runtimeFile) {
        $content = Get-Content $runtimeFile -Raw
        $content = $content -replace 'export const BASE_PATH = "https://api\.vitrown\.abrino\.cloud"', "import { getApiBaseUrl } from `"../../../app/utils/api-config`";`nexport const BASE_PATH = getApiBaseUrl()"
        $content = $content -replace 'export const BASE_PATH = "https://api\.vitrown\.com"', "import { getApiBaseUrl } from `"../../../app/utils/api-config`";`nexport const BASE_PATH = getApiBaseUrl()"
        Set-Content $runtimeFile $content
    }

    # Clean up
    Remove-Item "./openapi.json"
    Write-Host "API types generated successfully with dynamic BASE_PATH"
} catch {
    Write-Host "Error generating TypeScript types: $_"
    exit 1
}
