# Service Type Architecture

## System Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                     Service Type Enum                            │
│                  (Single Source of Truth)                        │
│                                                                   │
│  src/types/service-types.ts                                      │
│  ├── ServiceType enum (12 types)                                 │
│  ├── ServiceTypeMetadata (labels, icons, categories)             │
│  └── Helper functions (getServiceTypeLabel, etc.)                │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ imports
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                        TypeScript Types                          │
│                                                                   │
│  src/types/index.ts                                              │
│  ├── Tour.type: ServiceTypeValue                                 │
│  ├── AITourAnalysis.recommended_type: ServiceTypeValue           │
│  ├── TourRecommendation.recommended_type: ServiceTypeValue       │
│  └── RecommendationDisplayMetadata interface                     │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ used by
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Backend Layer                            │
│                                                                   │
│  Database (PostgreSQL)                                           │
│  ├── service_type ENUM                                           │
│  ├── tours.type: service_type                                    │
│  ├── tour_recommendations.recommended_type: service_type         │
│  └── tour_recommendations.display_* columns                      │
│                                                                   │
│  Edge Function (analyze-trip)                                    │
│  ├── generateDisplayMetadata()                                   │
│  ├── Returns AITourAnalysis with display_metadata                │
│  └── Personalizes based on traveler profile                      │
│                                                                   │
│  Service (provider-suggestions.ts)                               │
│  ├── Uses ServiceType enum                                       │
│  ├── Generates display metadata                                  │
│  └── Returns ProviderSuggestion with display_metadata            │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ consumed by
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Frontend Layer                           │
│                                                                   │
│  UI Components                                                   │
│  ├── AITourRecommendation.tsx                                    │
│  │   └── Uses analysis.display_metadata (AI-provided)            │
│  ├── TourModal.tsx                                               │
│  │   └── Uses analysis.display_metadata (AI-provided)            │
│  ├── TourCard.tsx                                                │
│  │   └── Uses getServiceTypeLabel(tour.type)                     │
│  └── AdminTours.tsx                                              │
│      └── Uses SERVICE_TYPE_METADATA for form options             │
└─────────────────────────────────────────────────────────────────┘
```

## Data Flow

### 1. AI Recommendation Flow

```
User creates trip
      │
      ▼
Edge Function: analyze-trip
      │
      ├─► Analyzes trip metrics
      ├─► Determines service type (ServiceTypeValue)
      ├─► Generates traveler profile
      ├─► Calls generateDisplayMetadata()
      │   ├─► Maps service type to label/icon
      │   └─► Personalizes segment message
      │
      ▼
Returns AITourAnalysis {
  recommended_type: 'daily_tour',
  display_metadata: {
    service_type_label: 'Günlük Tur',
    service_type_icon: '🗓️',
    group_label: 'Önerilen Turlar',
    segment_message: 'Çiftler için daha rahat...'
  },
  ...
}
      │
      ▼
UI Component (AITourRecommendation)
      │
      ├─► Reads display_metadata.service_type_label
      ├─► Reads display_metadata.service_type_icon
      ├─► Reads display_metadata.segment_message
      └─► Renders without any string matching
```

### 2. Tour Display Flow

```
Tour data from database
      │
      ▼
Tour {
  type: 'guided_tour' (ServiceTypeValue)
}
      │
      ▼
UI Component (TourCard)
      │
      ├─► Calls getServiceTypeLabel(tour.type)
      │   └─► Returns 'Rehberli Tur' from SERVICE_TYPE_METADATA
      │
      └─► Renders label
```

### 3. Admin Form Flow

```
Admin creates/edits tour
      │
      ▼
AdminTours component
      │
      ├─► Imports SERVICE_TYPE_METADATA
      ├─► Generates TOUR_TYPES array
      │   └─► Maps metadata to { value, label } pairs
      │
      ▼
Select dropdown
      │
      ├─► Shows all service types with labels
      └─► Validates against ServiceTypeValue type
```

## Key Principles

### 1. No UI String Matching
❌ **Before:**
```typescript
const typeLabels = { daily_tour: 'Günlük Tur', ... };
const label = typeLabels[type] || type;
```

✅ **After:**
```typescript
const label = analysis.display_metadata.service_type_label;
// OR
const label = getServiceTypeLabel(type);
```

### 2. AI-Driven Display
- Backend generates all display strings
- UI receives complete metadata
- No hardcoded labels in components

### 3. Type Safety
- TypeScript enforces valid service types
- Database enum prevents invalid values
- Compile-time error detection

### 4. Single Source of Truth
- All service types defined in one place
- Metadata centralized
- Easy to maintain and extend

## Component Responsibilities

### Backend (Edge Function)
- ✅ Determine service type
- ✅ Generate display metadata
- ✅ Personalize messaging
- ✅ Return complete data structure

### Frontend (UI Components)
- ✅ Render AI-provided metadata
- ✅ Use helper functions for fallbacks
- ❌ No string matching
- ❌ No hardcoded labels

### Shared (service-types.ts)
- ✅ Define service type enum
- ✅ Provide metadata
- ✅ Export helper functions
- ✅ Ensure type safety

## Extension Points

### Adding a New Service Type

1. **Update Enum:**
```typescript
// src/types/service-types.ts
export const ServiceType = {
  // ... existing types
  NEW_TYPE: 'new_type',
} as const;
```

2. **Add Metadata:**
```typescript
export const SERVICE_TYPE_METADATA = {
  // ... existing metadata
  [ServiceType.NEW_TYPE]: {
    value: ServiceType.NEW_TYPE,
    label: 'New Type Label',
    description: 'Description',
    icon: '🆕',
    category: 'tour',
  },
};
```

3. **Update Database:**
```sql
ALTER TYPE service_type ADD VALUE 'new_type';
```

4. **Update Edge Function:**
```typescript
// Add to generateDisplayMetadata() if needed
const serviceTypeMetadata = {
  // ... existing mappings
  'new_type': { label: 'New Type Label', icon: '🆕' },
};
```

That's it! No UI changes needed.

### Customizing Display Metadata

The `generateDisplayMetadata()` function can be enhanced to:
- Support multiple languages
- Use different icons per theme
- Generate context-specific messages
- Include pricing information
- Add promotional badges

Example:
```typescript
function generateDisplayMetadata(
  serviceType: ServiceTypeValue,
  travelerProfile: TravelerProfile,
  options?: {
    language?: 'tr' | 'en';
    theme?: 'default' | 'premium';
    includePromo?: boolean;
  }
): RecommendationDisplayMetadata {
  // Custom logic here
}
```

## Testing Checklist

- [ ] TypeScript compilation passes
- [ ] Lint passes without errors
- [ ] All service types display correct labels
- [ ] AI responses include display_metadata
- [ ] Database enum constraint works
- [ ] Admin form shows all service types
- [ ] Tour cards render correctly
- [ ] Recommendation cards show personalized messages
- [ ] No hardcoded labels in UI components
- [ ] Helper functions return correct values
