# Music Monitor API Contract

Documentazione ufficiale del contratto API per l'integrazione frontend (SolidJS / SolidStart con Vite e Bun).

## Informazioni Generali
- **Base URL**: `/api` (es. `http://192.168.178.100:8000/api`)
- **Configurazione Vite (`.env`)**:
  ```env
  VITE_API_URL=http://192.168.178.100:8000
  ```
- **Content-Type**: `application/json`
- **Accept**: `application/json`

---

## Modelli di Autenticazione (Laravel Sanctum)

Il backend supporta due modalità distinte di autenticazione:

### Modalità A: SPA Stateful (Consigliata per SolidJS SPA)
Utilizza i cookie di sessione HTTP-only di Laravel Sanctum protetti da CSRF.
1. Richiedere il cookie CSRF: `GET /sanctum/csrf-cookie` (`credentials: 'include'`).
2. Leggere il cookie `XSRF-TOKEN` dal browser.
3. Inviare l'header `X-XSRF-TOKEN` insieme a `credentials: 'include'` su ogni richiesta mutativa (`POST`, `PUT`, `DELETE`).

### Modalità B: Stateless Client (Bearer Token)
Utilizza un token di accesso statico o generato al login.
- Header richiesto: `Authorization: Bearer <access_token>`

---

## Endpoint Dettagliati

### 1. POST /api/login
Autenticazione dell'utente e avvio della sessione SPA / generazione token Bearer.

- **Headers**:
  - `Content-Type: application/json`
  - `Accept: application/json`
  - `X-XSRF-TOKEN: <valore_cookie_xsrf>` (necessario per Modalità A)
- **Request Body (JSON)**:
  ```json
  {
    "email": "admin@musicmonitor.test",
    "password": "password"
  }
  ```
- **Validation Rules**: `email` (required, email), `password` (required).
- **Response 200 OK**:
  ```json
  {
    "status": "success",
    "message": "Login effettuato con successo.",
    "access_token": "1|UYpiKaP1Jpu5iDyLVfBo1jKpHqjuNPmuvXY7JuNsb945a3dd",
    "token_type": "Bearer",
    "user": {
      "id": 1,
      "name": "Administrator",
      "email": "admin@musicmonitor.test"
    }
  }
  ```
- **Error Responses**:
  - `401 Unauthorized`: Credenziali non valide (`{"status": "error", "message": "Credenziali non valide."}`)
  - `422 Unprocessable Entity`: Validazione fallita
  - `429 Too Many Requests`: Rate limit superato

### 2. POST /api/logout
Termina la sessione SPA o revoca il token Bearer.
- **Headers**: `Authorization: Bearer <token>` o cookie Sanctum + `X-XSRF-TOKEN`.
- **Response 200 OK**: `{"status": "success", "message": "Logout effettuato con successo."}`

### 3. GET /api/me
Restituisce i dati dell'utente autenticato corrente.
- **Response 200 OK**: Dati utente.
- **Error 401**: Non autenticato.

### 4. POST /api/search
Ricerca ibrida (vettoriale `pgvector` + filtri deterministici).
- **Request Body (JSON)**:
  ```json
  {
    "query": "Techno DJ in Berlin",
    "limit": 10,
    "threshold": 0.70,
    "country_iso2": "DE",
    "department": "Music"
  }
  ```
- **Validation Rules**:
  - `query`: required, string, min 2 chars
  - `limit`: optional, integer (1-50)
  - `threshold`: optional, float (0.0 - 1.0)
  - `country_iso2`: optional, 2 chars ISO
  - `department`: optional, string
- **Response 200 OK**: Elenco contatti con score di similarità.
- **Error 503 Service Unavailable (Ollama Offline)**:
  ```json
  {
    "error": "Servizio Ollama non raggiungibile o impossibile generare embedding"
  }
  ```

---

## Gestione Ollama Offline (Fallback & Test)
Quando il servizio Ollama (`http://192.168.178.186:11434`) è offline o irraggiungibile:
- L'endpoint `/api/health` restituisce stato `"degraded"` o servizi `"down"`.
- L'endpoint `/api/search` intercetta l'errore di connessione e restituisce immediatamente HTTP `503 Service Unavailable` con il JSON di errore descritto sopra.
- **Come testare il fallback**: Interrompere temporaneamente il servizio Ollama (o puntare `OLLAMA_BASE_URL` su una porta non attiva) ed eseguire una ricerca su `/api/search`.

---

### Esempio Client SolidJS / TypeScript (per Giacomo)

```typescript
const VITE_API_URL = import.meta.env.VITE_API_URL ?? 'http://192.168.178.100:8000';
const API_URL = `${VITE_API_URL}/api`;
const BASE_URL = VITE_API_URL;

// Helper per leggere il cookie XSRF-TOKEN di Sanctum
function getCookie(name: string): string | null {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  return match ? decodeURIComponent(match[2]) : null;
}

export async function getCsrfCookie(): Promise<void> {
  await fetch(`${BASE_URL}/sanctum/csrf-cookie`, {
    credentials: 'include',
  });
}

export async function login(email: string, password: string) {
  await getCsrfCookie();
  const xsrfToken = getCookie('XSRF-TOKEN');

  const res = await fetch(`${API_URL}/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      ...(xsrfToken ? { 'X-XSRF-TOKEN': xsrfToken } : {}),
    },
    credentials: 'include',
    body: JSON.stringify({ email, password }),
  });

  if (!res.ok) {
    if (res.status === 401) throw new Error('Credenziali non valide.');
    if (res.status === 422) throw new Error('Errore di validazione.');
    if (res.status === 429) throw new Error('Troppi tentativi. Riprova più tardi.');
    throw new Error('Errore di sistema.');
  }

  return await res.json();
}

export async function getMe() {
  const res = await fetch(`${API_URL}/me`, {
    headers: { 'Accept': 'application/json' },
    credentials: 'include',
  });

  if (!res.ok) throw new Error('Non autenticato.');
  return await res.json();
}

export async function searchContacts(query: string, signal?: AbortSignal) {
  const xsrfToken = getCookie('XSRF-TOKEN');

  const res = await fetch(`${API_URL}/search`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      ...(xsrfToken ? { 'X-XSRF-TOKEN': xsrfToken } : {}),
    },
    credentials: 'include',
    body: JSON.stringify({ query }),
    signal,
  });

  if (res.status === 503) {
    throw new Error('Servizio AI (Ollama) attualmente non disponibile.');
  }
  if (!res.ok) {
    throw new Error('Errore durante la ricerca.');
  }

  return await res.json();
}

export async function logout() {
  const xsrfToken = getCookie('XSRF-TOKEN');
  await fetch(`${API_URL}/logout`, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      ...(xsrfToken ? { 'X-XSRF-TOKEN': xsrfToken } : {}),
    },
    credentials: 'include',
  });
}
```
