#!/bin/bash
# Generate TypeScript types from OpenAPI specification
# Usage: ./scripts/generate-types.sh

set -e

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Paths
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
BACKEND_ROOT="$(cd "$PROJECT_ROOT/../../veza-backend-api" && pwd)"
OPENAPI_SPEC="$BACKEND_ROOT/openapi.yaml"
OUTPUT_DIR="$PROJECT_ROOT/src/types/generated"

echo -e "${GREEN}🔨 Generating TypeScript types from OpenAPI spec...${NC}"

# Check if OpenAPI spec exists
if [ ! -f "$OPENAPI_SPEC" ]; then
    echo -e "${RED}❌ Error: OpenAPI spec not found at $OPENAPI_SPEC${NC}"
    echo -e "${YELLOW}   Please ensure veza-backend-api/openapi.yaml exists${NC}"
    exit 1
fi

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Generate types using openapi-generator-cli
echo -e "${GREEN}📝 Generating types from $OPENAPI_SPEC${NC}"
echo -e "${GREEN}📦 Output directory: $OUTPUT_DIR${NC}"

npx @openapitools/openapi-generator-cli generate \
    -i "$OPENAPI_SPEC" \
    -g typescript-axios \
    -o "$OUTPUT_DIR" \
    --additional-properties=supportsES6=true,withInterfaces=true,typescriptThreePlus=true

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Types generated successfully to $OUTPUT_DIR${NC}"
    
    # Create index.ts barrel export
    echo -e "${GREEN}📦 Creating barrel export...${NC}"
    cat > "$OUTPUT_DIR/index.ts" << 'EOF'
// Auto-generated types from OpenAPI specification
// Do not edit this file manually - it will be overwritten

export * from './api';
export * from './base';
export * from './configuration';
export * from './common';
EOF
    
    echo -e "${GREEN}✅ Type generation complete!${NC}"
    echo -e "${YELLOW}⚠️  Note: Review generated types and update imports as needed${NC}"
else
    echo -e "${RED}❌ Type generation failed${NC}"
    exit 1
fi
