#!/bin/bash
# Validate that generated types match the committed types.
# This script is designed to run in CI/CD pipelines to prevent type drift.
# 
# Exit codes:
#   0 — types are in sync
#   1 — types are out of sync
#   2 — backend is not accessible
#   3 — generation failed

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRONTEND_DIR="$(dirname "$SCRIPT_DIR")"
TYPES_DIR="${FRONTEND_DIR}/src/types"
GENERATED_FILE="${TYPES_DIR}/generated.ts"
TEMP_FILE=$(mktemp)
trap "rm -f $TEMP_FILE" EXIT

# Check if backend is accessible
BACKEND_URL="${BANGUI_BACKEND_URL:-http://localhost:8000}"
if ! curl -sf "${BACKEND_URL}/api/openapi.json" > /dev/null 2>&1; then
  echo "❌ Backend not accessible at ${BACKEND_URL}/api/openapi.json" >&2
  exit 2
fi

echo "📋 Validating OpenAPI schema types..."

# Generate types to a temporary file
if ! npx openapi-typescript "${BACKEND_URL}/api/openapi.json" -o "$TEMP_FILE" 2>&1; then
  echo "❌ Failed to generate types from OpenAPI schema" >&2
  exit 3
fi

# Compare with committed generated types
if ! diff -u "$GENERATED_FILE" "$TEMP_FILE" > /dev/null 2>&1; then
  echo "❌ Generated types differ from committed types" >&2
  echo ""
  echo "Run 'npm run generate:types' to update types, then commit the changes:"
  diff -u "$GENERATED_FILE" "$TEMP_FILE" || true
  exit 1
fi

echo "✅ Types are in sync with backend schema"
exit 0
