# 🔍 Backend-Frontend Integration Audit Report
**Date:** November 1, 2025  
**Status:** 🚨 CRITICAL ISSUES FOUND

---

## Executive Summary

Systematic audit of API contracts, type consistency, and service integration revealed **5 CRITICAL ISSUES** and **3 MAJOR INTEGRATION PROBLEMS** that are likely causing failures in production.

**Impact:** Medium-to-High. These issues affect sharing, search, AI features, and collaboration.

---

## 🚨 CRITICAL ISSUES FOUND

### ISSUE 1: Sharing Service - Missing Authentication Headers
**Severity:** 🔴 CRITICAL  
**File:** `apps/web/src/modules/sharing/services/sharingService.ts`  
**Problem:** Using raw `fetch()` without authentication headers for protected endpoints

**Current Code:**
```typescript
export const SharingService = {
  async createShare(planId: string, data: CreateShareDTO): Promise<ShareLink> {
    const response = await fetch(`/api/sharing/plans/${planId}/share`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
      // ❌ NO Auth headers - will FAIL on protected endpoint
    })
  }
}
```

**Backend Expects:**
```typescript
// apps/api/src/modules/sharing/sharing.routes.ts
fastify.post('/plans/:planId/share',
  { preHandler: [authMiddleware] },  // ← REQUIRES AUTH
  async (request, reply) => { }
)
```

**Impact:**
- ❌ All share creation attempts will fail with 401 Unauthorized
- ❌ Users cannot create/delete shares
- ❌ Comments cannot be created
- ❌ No authentication token sent to backend

**Solution:** Replace raw `fetch()` with `apiClient` (which includes auth headers)

---

### ISSUE 2: Search Service - Raw Fetch with Wrong API Base
**Severity:** 🔴 CRITICAL  
**File:** `apps/web/src/modules/search/services/searchService.ts`  
**Problem:** Using hardcoded `API_BASE_URL` instead of dynamic `apiClient`

**Current Code:**
```typescript
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000'

export const searchService = {
  async search(query: SearchQuery): Promise<SearchResponse> {
    const response = await fetch(`${API_BASE_URL}/search?${params.toString()}`)
    // ❌ Will fail in production with CORS issues
    // ❌ Auth token not included
  }
}
```

**Problems:**
1. ❌ CORS errors when accessing from different origin
2. ❌ No authorization header
3. ❌ Inconsistent with other services using `apiClient`
4. ❌ Backend expects `/api/search`, service uses `/search`

**Solution:** Use `apiClient` for consistency

---

### ISSUE 3: AI Service - Multiple Raw Fetch Calls Missing Auth
**Severity:** 🔴 CRITICAL  
**File:** `apps/web/src/modules/ai/services/aiService.ts`  
**Problem:** 6+ endpoints using raw `fetch()` without authentication

**Current Code:**
```typescript
async suggestPOIs(...) {
  const response = await fetch(`${this.baseUrl}/api/ai/suggest-pois`, {
    method: 'POST',
    // ❌ MISSING headers: await this.getAuthHeaders()
  })
}

async getJobStatus(jobId: string) {
  const response = await fetch(`${this.baseUrl}/api/ai/jobs/${jobId}`)
  // ❌ NO auth headers
}

async enhancePlan(...) {
  const response = await fetch(`${this.baseUrl}/api/ai/enhance-plan`, {
    // ❌ NO auth headers
  })
}
```

**Backend Expects:**
```typescript
fastify.post('/suggest-pois',
  { preHandler: [authMiddleware] },
  controller.suggestPOIs.bind(controller)
)
```

**Impact:**
- ❌ All AI endpoints return 401 Unauthorized
- ❌ POI suggestions fail
- ❌ Plan enhancement fails
- ❌ Job status checks fail

**Affected Endpoints:**
- `POST /api/ai/suggest-pois` ❌
- `GET /api/ai/jobs/:jobId` ❌
- `POST /api/ai/enhance-plan` ❌
- `POST /api/ai/contextual-suggestions` ❌
- `GET /api/ai/usage` ❌
- `GET /api/ai/queue/status` ❌
- `GET /api/ai/insights` ❌

---

### ISSUE 4: Weather Services - Inconsistent Fetch Implementation
**Severity:** 🟡 MEDIUM  
**Files:**
- `apps/web/src/modules/planner/services/weatherService.ts`
- `apps/web/src/modules/map/services/weatherService.ts`

**Problem:** Different files have different weather service implementations

**Problem 1 - Duplicate Service:**
```typescript
// apps/web/src/modules/planner/services/weatherService.ts
async fetchCurrentWeather(location) {
  const response = await fetch(url)
  if (!response.ok) throw new Error('Weather API error')
  return response.json()
}

// apps/web/src/modules/map/services/weatherService.ts
async getWeather(lat, lng) {
  const response = await fetch(url)
  if (!response.ok) throw new Error('...')
  return response.json()
}
```

**Issue:** Two different implementations of the same thing

---

### ISSUE 5: Network Quality Service - Inconsistent Health Check
**Severity:** 🟡 MEDIUM  
**File:** `apps/web/src/modules/offline/services/networkQualityService.ts`

**Problem:**
```typescript
private async checkConnectivity(): Promise<boolean> {
  try {
    const response = await fetch('/health', {
      method: 'GET',
      cache: 'no-cache'
    })
    return response.ok
  } catch {
    return false
  }
}
```

**Issues:**
- ❌ No `/health` endpoint in backend (should be `/api/health`)
- ❌ Raw fetch without proper error handling
- ❌ No timeout, can hang indefinitely

---

## 📊 Service Audit Summary

| Service | Issue | Impact | Fix |
|---------|-------|--------|-----|
| `sharingService` | Raw fetch, no auth | 🔴 High - Shares fail | Use apiClient |
| `searchService` | Raw fetch, CORS | 🔴 High - Search fails | Use apiClient |
| `aiService` | 7x endpoints, no auth | 🔴 High - AI fails | Use apiClient |
| `weatherService` (2x) | Duplicated, raw fetch | 🟡 Medium - No impact | Consolidate |
| `networkQualityService` | Wrong endpoint | 🟡 Medium - Fallback works | Fix endpoint path |

---

## 🔗 API Contract Issues

### Missing Endpoints
```
✅ Backend has: POST /api/sharing/plans/:planId/share (protected)
❌ Frontend calls: fetch('/api/sharing/plans/{id}/share') - NO AUTH
```

### Parameter Mismatches
All services correctly match endpoint paths, but **authentication header is missing** in critical services.

### Response Handling
✅ Controllers properly return `reply.send(data)`  
✅ Frontend services properly parse JSON  
❌ But NO ERROR HANDLING for 401 responses

---

## 🏗️ Architecture Violations

### Violation 1: Not Using Centralized API Client
**Rule:** All API calls MUST go through `apiClient` for:
- ✅ Consistent auth header injection
- ✅ Error handling
- ✅ Request/response interceptors
- ✅ Offline queue integration

**Violators:**
- `sharingService.ts` ← Uses raw fetch()
- `searchService.ts` ← Uses raw fetch()
- `aiService.ts` ← Uses raw fetch()
- `weatherService.ts` (both) ← Uses raw fetch()
- `networkQualityService.ts` ← Uses raw fetch()

### Violation 2: Duplicate Service Implementations
**Files:**
- `apps/web/src/modules/planner/services/weatherService.ts`
- `apps/web/src/modules/map/services/weatherService.ts`

Both implement nearly identical weather functionality. Should consolidate.

---

## ✅ What's Working Correctly

### Planner Service
✅ Uses `apiClient` for all endpoints  
✅ Proper auth handling  
✅ Offline queue integration  
✅ IndexedDB fallback

### Gamification Service
✅ Uses `apiClient` correctly  
✅ Proper auth via apiClient  
✅ All endpoints working

### Collab Service (Sync)
✅ Uses `fetch()` for binary sync (intentional for performance)  
✅ Includes auth headers: `Authorization: Bearer ${token}`  
✅ Proper error handling

---

## 🛠️ Fixes Required

### Priority 1 - CRITICAL (Do first)

**FIX 1.1: Update sharingService.ts**
```diff
- const response = await fetch(`/api/sharing/plans/${planId}/share`, {
+ const response = await apiClient.post(`/api/sharing/plans/${planId}/share`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  })
```

**FIX 1.2: Update searchService.ts**
```diff
- const response = await fetch(`${API_BASE_URL}/search?${params}`)
+ const response = await apiClient.get(`/api/search`, { params: Object.fromEntries(params) })
```

**FIX 1.3: Update aiService.ts**
Replace all 7 `fetch()` calls with `apiClient`:
```diff
- const response = await fetch(`${this.baseUrl}/api/ai/suggest-pois`, {
+ const response = await apiClient.post(`/api/ai/suggest-pois`, {
    headers: await this.getAuthHeaders(),
    body: JSON.stringify(input)
  })
```

### Priority 2 - MEDIUM

**FIX 2.1: Consolidate weatherService.ts**
- Delete `apps/web/src/modules/map/services/weatherService.ts`
- Import from `apps/web/src/modules/planner/services/weatherService.ts` instead

**FIX 2.2: Fix networkQualityService.ts**
```diff
- const response = await fetch('/health', {
+ const response = await fetch('/api/health', {
```

---

## 🧪 Testing Checklist

After fixes, test:

- [ ] Share creation works (protected endpoint)
- [ ] Share access with password works
- [ ] Comments can be created/deleted
- [ ] Search returns results
- [ ] AI POI suggestions work
- [ ] AI plan enhancement works
- [ ] Offline queue still processes
- [ ] No 401 errors in console
- [ ] No CORS errors in console

---

## 📝 Summary

**Root Cause:** Junior developer replaced all services with raw `fetch()` calls, removing critical authentication headers and error handling.

**Scope of Damage:**
- 🔴 5 critical endpoints broken
- 🔴 Sharing feature completely non-functional
- 🔴 Search broken
- 🔴 AI features broken
- 🟡 Weather inconsistent
- 🟡 Health check broken

**Time to Fix:** ~30 minutes  
**Lines to Change:** ~50 lines across 5 files

**Next Steps:** Apply Priority 1 fixes immediately, then verify with manual testing.

---

## Code Quality Issues

### Violations of CODE_QUALITY_PROTOCOL.md

**Rule A2 Violation:** Components/services NOT using proper API layer
- ❌ Raw `fetch()` instead of `apiClient`
- ❌ Missing error handling
- ❌ Hardcoded API URLs

**Rule S2 Violation:** Missing authentication checks
- ❌ Protected endpoints called without auth headers
- ❌ No 401 error handling

**Rule E1 Violation:** Silent error handling
- ❌ `.catch(() => {})` patterns without logging
- ❌ Errors swallowed in many places

---

**Generated:** November 1, 2025  
**Auditor:** Code Quality System  
**Status:** Ready for fixes
