# Service Type Enum Refactoring

## Overview

This refactoring introduces a clear, shared service type enum system that eliminates UI-side string matching and ensures all grouping and labels are driven by AI output.

## Key Changes

### 1. **Shared Service Type Enum** (`src/types/service-types.ts`)

Created a centralized enum that defines all service types with complete metadata:

```typescript
export const ServiceType = {
  DAILY_TOUR: 'daily_tour',
  PRIVATE_GUIDE: 'private_guide',
  DRIVER_CAR: 'driver_car',
  ACTIVITY_BUNDLE: 'activity_bundle',
  HOT_AIR_BALLOON: 'hot_air_balloon',
  ATV: 'atv',
  HORSE_RIDING: 'horse_riding',
  GUIDED_TOUR: 'guided_tour',
  MUSEUM_TOUR: 'museum_tour',
  ADVENTURE: 'adventure',
  CULTURAL: 'cultural',
  NATURE: 'nature',
} as const;
```

Each service type includes:
- **Value**: The enum value (e.g., 'daily_tour')
- **Label**: Display label (e.g., 'Günlük Tur')
- **Description**: Human-readable description
- **Icon**: Emoji/icon for visual representation
- **Category**: Grouping category (tour/private/activity/specialized)

### 2. **Display Metadata Interface**

Added `RecommendationDisplayMetadata` interface to carry AI-generated display information:

```typescript
interface RecommendationDisplayMetadata {
  service_type_label: string;      // e.g., "Günlük Tur"
  service_type_icon?: string;      // e.g., "🗓️"
  group_label?: string;            // e.g., "Önerilen Turlar"
  group_description?: string;      // e.g., "Günlük Tur ile daha iyi bir deneyim"
  segment_message?: string;        // Personalized based on traveler profile
}
```

### 3. **Database Schema Updates**

Created PostgreSQL enum type and added display metadata columns:

```sql
-- Create service type enum
CREATE TYPE service_type AS ENUM (
  'daily_tour',
  'private_guide',
  'driver_car',
  'activity_bundle',
  'hot_air_balloon',
  'atv',
  'horse_riding',
  'guided_tour',
  'museum_tour',
  'adventure',
  'cultural',
  'nature'
);

-- Add display metadata columns
ALTER TABLE tour_recommendations
  ADD COLUMN display_service_type_label TEXT,
  ADD COLUMN display_service_type_icon TEXT,
  ADD COLUMN display_group_label TEXT,
  ADD COLUMN display_group_description TEXT,
  ADD COLUMN display_segment_message TEXT;
```

### 4. **TypeScript Type Updates**

Updated all relevant interfaces to use the new enum:

- `Tour.type`: Now uses `ServiceTypeValue`
- `AITourAnalysis.recommended_type`: Now uses `ServiceTypeValue`
- `TourRecommendation.recommended_type`: Now uses `ServiceTypeValue`
- Added `display_metadata` field to `AITourAnalysis` and `TourRecommendation`

### 5. **UI Component Refactoring**

#### Before (String Matching):
```typescript
// ❌ OLD: UI infers labels from hardcoded mapping
const typeLabels: Record<string, string> = {
  daily_tour: 'Günlük Tur',
  private_guide: 'Özel Rehber',
  // ... hardcoded mappings
};

const label = typeLabels[analysis.recommended_type] || analysis.recommended_type;
```

#### After (AI-Driven):
```typescript
// ✅ NEW: UI uses AI-provided metadata
const serviceTypeMetadata = getServiceTypeMetadata(analysis.recommended_type);
const displayLabel = analysis.display_metadata?.service_type_label || serviceTypeMetadata.label;
const displayIcon = analysis.display_metadata?.service_type_icon || serviceTypeMetadata.icon;
```

Updated components:
- `AITourRecommendation.tsx`: Uses `display_metadata` from AI response
- `TourModal.tsx`: Uses `display_metadata` for dialog title and description
- `TourCard.tsx`: Uses `getServiceTypeLabel()` helper
- `AdminTours.tsx`: Uses `SERVICE_TYPE_METADATA` for form options

### 6. **Backend Service Updates**

#### Provider Suggestions Service (`src/services/provider-suggestions.ts`)

Updated to generate display metadata:

```typescript
function generateDisplayMetadata(
  serviceType: ServiceTypeValue,
  travelerProfile?: TravelerProfile
): RecommendationDisplayMetadata {
  const metadata = getServiceTypeMetadata(serviceType);
  
  // Generate personalized segment message
  let segmentMessage = '...';
  if (travelerProfile?.group_type === 'couple') {
    segmentMessage = 'Çiftler için daha rahat ve romantik bir deneyim sunabilir.';
  }
  // ... more personalization logic
  
  return {
    service_type_label: metadata.label,
    service_type_icon: metadata.icon,
    group_label: 'Önerilen Turlar',
    group_description: `${metadata.label} ile daha iyi bir deneyim`,
    segment_message: segmentMessage,
  };
}
```

#### Edge Function (`supabase/functions/analyze-trip/index.ts`)

Added `generateDisplayMetadata()` function that:
1. Maps service types to labels and icons
2. Generates personalized messages based on traveler profile
3. Returns complete display metadata in all responses

All response paths now include `display_metadata`:
- Rule-based recommendations
- Fallback recommendations
- AI-generated recommendations

## Benefits

### 1. **Single Source of Truth**
- Service types defined once in `service-types.ts`
- No duplicate mappings across codebase
- Easy to add new service types

### 2. **Type Safety**
- TypeScript enforces valid service type values
- Compile-time errors for invalid types
- Better IDE autocomplete

### 3. **AI-Driven UI**
- All labels and grouping come from backend
- UI doesn't need to know about service types
- Easy to A/B test different messaging

### 4. **Consistency**
- Same labels used everywhere
- Database, backend, and frontend aligned
- No string matching or inference

### 5. **Personalization**
- Segment-specific messaging based on traveler profile
- Dynamic labels based on context
- Better user experience

## Migration Guide

### For New Features

When adding a new service type:

1. Add to `ServiceType` enum in `service-types.ts`
2. Add metadata to `SERVICE_TYPE_METADATA`
3. Update database enum: `ALTER TYPE service_type ADD VALUE 'new_type'`
4. No UI changes needed - automatically available

### For Existing Code

To use service types in new components:

```typescript
import { getServiceTypeLabel, getServiceTypeMetadata } from '@/types/service-types';

// Get just the label
const label = getServiceTypeLabel(tour.type);

// Get full metadata
const metadata = getServiceTypeMetadata(tour.type);
console.log(metadata.label, metadata.icon, metadata.category);
```

## Testing

Verify the refactoring:

1. **Type Safety**: Run `npm run lint` - should pass without errors
2. **UI Rendering**: Check that all service type labels display correctly
3. **AI Responses**: Verify `display_metadata` is present in API responses
4. **Database**: Confirm enum constraint works for tours and recommendations

## Future Enhancements

1. **Localization**: Add language parameter to `generateDisplayMetadata()`
2. **Dynamic Icons**: Support custom icon sets per theme
3. **Category Filtering**: Use `category` field for advanced filtering
4. **Analytics**: Track which service types convert best
