#!/bin/bash
# Update API Client from OpenAPI Specification
#
# This script regenerates Dart API client code from the OpenAPI contract.
# Run this after the backend team updates docs/openapi.json

set -e  # Exit on error

echo "🔄 Updating API Client from OpenAPI Specification..."
echo ""

# Check if api-schema.json exists
if [ ! -f "api-schema.json" ]; then
    echo "❌ Error: api-schema.json not found"
    echo ""
    echo "Please copy the OpenAPI spec from backend:"
    echo "  cp ../backend/docs/openapi.json ./api-schema.json"
    echo ""
    exit 1
fi

# Show schema info
SCHEMA_SIZE=$(wc -c < api-schema.json | tr -d ' ')
echo "📄 OpenAPI Schema: api-schema.json (${SCHEMA_SIZE} bytes)"
echo ""

# Check if backend CHANGELOG exists and show recent changes
if [ -f "../backend/docs/CHANGELOG.md" ]; then
    echo "📋 Recent Backend Changes:"
    echo "────────────────────────────"
    head -n 20 ../backend/docs/CHANGELOG.md | grep -v "^#" | grep -v "^$" || echo "No recent changes"
    echo "────────────────────────────"
    echo ""
fi

# Run build_runner to generate code
echo "🏗️  Running code generation..."
echo ""

flutter pub run build_runner build --delete-conflicting-outputs

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ API client updated successfully!"
    echo ""
    echo "Next steps:"
    echo "  1. Review generated types in lib/api/generated/"
    echo "  2. Update endpoint extensions if needed"
    echo "  3. Run tests: flutter test"
    echo "  4. Commit changes: git add . && git commit -m 'chore: Update API client'"
    echo ""
else
    echo ""
    echo "❌ Code generation failed"
    echo ""
    echo "Troubleshooting:"
    echo "  1. Check api-schema.json is valid OpenAPI 3.x"
    echo "  2. Run: flutter clean && flutter pub get"
    echo "  3. Check build errors above"
    echo ""
    exit 1
fi
