> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Search — Outlet API handoff (dashboard)

> **Verification boundary:** The detailed contract below was derived from repository source, not from live HTTP captures. Fields explicitly marked unverified remain open. The earlier route inventory is retained below for cross-checking; where it says “not verified”, the more recent source-reviewed contract takes precedence.

## Controller-reviewed contracts


**Source:** GitLab project `alalmiyalhura/outlet`, `main`, inspected 2026-11-22. **Base path:** `/api/v1`. **Status:** code-reviewed contracts; examples are illustrative, not live API captures.

**Sources:**
- `modules/Search/Routes/api.php`
- `modules/Search/Interfaces/Http/Controllers/SearchController.php`
- `modules/Search/Application/FederatedSearch.php`
- `modules/Search/Domain/SearchHit.php`
- `modules/Search/Infrastructure/DatabaseSearchAnalytics.php`
- `modules/Search/Infrastructure/UsersSource.php`

All endpoints require `Authorization: Bearer <Sanctum token>` and `Accept: application/json`. Errors follow the project's shared API error handling; exact error codes for every failure have **not** been verified by running the backend. Do not treat sample result records as production data.

## 1. GET `/api/v1/search`

**Audience:** authenticated clients, including global search UIs. **Purpose:** federated search across registered sources, limited to sources for which the current user has permission. **Throttle:** configurable `search.throttle_per_minute` (default 60/minute). No request body.

### Query contract

| Field | Type | Required | Validation/default | Meaning |
|---|---|---|---|---|
| `q` | string | Yes | `max:100` | Raw search phrase; normalized internally. |
| `types` | string | No | `max:200` | Comma-separated source types, e.g. `users`; unknown or unauthorized types silently ignored. |
| `limit` | integer | No | 1–50, default 10 | Maximum number of returned hits across all sources. |

### Request

```http
GET /api/v1/search?q=ahmed&types=users&limit=10 HTTP/1.1
Authorization: Bearer <token>
Accept: application/json
```

### Success — HTTP 200

```json
{
  "data": {
    "query": "ahmed",
    "total": 1,
    "by_type": {"users": 1},
    "results": [
      {"type": "users", "id": "42", "title": "Ahmed Ali", "subtitle": "ahmed@example.test", "url": "/api/v1/admin/users/42", "score": 125}
    ]
  }
}
```

### Response fields

| JSON path | Type | Notes |
|---|---|---|
| `data.query` | string | Original query as represented by `SearchQuery.raw`. |
| `data.total` | integer | Count of returned hits **after** global `limit`, not unbounded database total. |
| `data.by_type` | object<string, integer> | Number of hits found per consulted source **before** global truncation; omitted source types may be unauthorized, unregistered, or failed. |
| `data.results` | array<object> | Ranked result list, at most `limit` elements. |
| `data.results[].type` | string | Registered search source type. |
| `data.results[].id` | string | Source-specific identifier, always serialized as string by `SearchHit`. |
| `data.results[].title` | string | Primary display text. |
| `data.results[].subtitle` | string/null | Optional secondary text. |
| `data.results[].url` | string/null | Optional navigation URL. |
| `data.results[].score` | integer | Internal ranking score; do not display as a rating. |

**Behavior:** hits are merged and ranked across sources; errors from an individual source are reported internally and skipped, rather than failing the whole request. Analytics recording errors are also nonfatal. User records are included only when the caller has `users.view`; their result URL points to the admin user endpoint. No pagination or `page` parameter exists for this route.

**Possible failures:** 401 unauthenticated, 422 invalid query (`q`, `types`, `limit`), 429 rate limit. Exact error body/codes require runtime confirmation.

## 2. POST `/api/v1/search/clicks`

**Audience:** authenticated clients. **Purpose:** record that a user clicked a search result for analytics; does **not** open the result on the server. **Throttle:** 120/minute.

### JSON body contract

| Field | Type | Required | Validation | Meaning |
|---|---|---|---|---|
| `q` | string | Yes | `max:100` | Search term, folded before recording. |
| `type` | string | Yes | `max:40` | Type of selected result. |
| `id` | string | Yes | `max:64` | Identifier of selected result. |

### Request

```http
POST /api/v1/search/clicks HTTP/1.1
Authorization: Bearer <token>
Content-Type: application/json
Accept: application/json

{"q":"ahmed","type":"users","id":"42"}
```

### Success — HTTP 204

**Empty response body** (`ApiResponse::noContent()`). Do not expect a JSON `data` property or attempt to decode an empty response as JSON.

**Behavior:** records normalized term, type, result reference and authenticated user ID. The controller does not validate that `type`/`id` actually identify an existing result. Clients should send the exact `type` and `id` from a preceding search result. **Possible failures:** 401, 422, 429; DB errors could cause 5xx.

## 3. GET `/api/v1/search/analytics`

**Audience:** Dashboard only. **Auth:** Sanctum **plus `search.analytics` permission**. **Purpose:** top search terms and terms for which all recorded searches returned zero results. No request body.

### Query contract

| Field | Type | Required | Default/behavior |
|---|---|---|---|
| `days` | integer-like query value | No | Default 30; converted to integer and clamped to 1–365, **not rejected** when out of range. |

### Request

```http
GET /api/v1/search/analytics?days=30 HTTP/1.1
Authorization: Bearer <admin-token>
Accept: application/json
```

### Success — HTTP 200

```json
{
  "data": {
    "top": [
      {"term":"ahmed","searches":25,"avg_results":4.32}
    ],
    "zero_results": [
      {"term":"unknown product","searches":8,"avg_results":0}
    ]
  }
}
```

### Response fields

| JSON path | Type | Meaning |
|---|---|---|
| `data.top` | array<object> | Up to 20 most frequent normalized search terms during period. |
| `data.zero_results` | array<object> | Up to 20 terms whose **sum of recorded result counts is zero** during period. |
| `[].term` | string | Normalized term, stored at most 100 characters. |
| `[].searches` | integer | Number of recorded queries for the term. |
| `[].avg_results` | number | Average recorded returned result count, rounded to 2 decimal places. |

**Behavior:** analytics groups by normalized term, sorts by descending number of searches and then term, and restricts data to the selected recent-day window. A zero-results term means *every recorded search* for it returned zero results, not merely that one search did. These aggregates are **not shown as tenant-filtered** in the inspected implementation; confirm access policy before exposing to tenant-specific dashboards.

**Possible failures:** 401 unauthenticated, 403 missing `search.analytics`, server/database errors. The `days` field is clamped, so values like `999` do not produce 422 solely due to range.

## Screen handoff

| UI | Endpoint | Integration guidance |
|---|---|---|
| Authenticated search bar / search results | `GET /search` | Debounce input; display `title`, `subtitle`; navigate using result `url` only after checking supported route. |
| Search result selection | `POST /search/clicks` | Fire on user selection; HTTP 204 means success with no body. |
| Dashboard search analytics | `GET /search/analytics` | Requires `search.analytics`; render top terms and zero-result terms separately. |

## Verification boundary

These three paths and controller contracts were checked directly against the GitLab `main` branch. This document **does not certify** deployed behavior, actual Flutter/Dashboard screen wiring, or precise shared exception-handler payloads. No endpoints were added or changed in the repository.


---

## Earlier route inventory (historical; superseded by contracts above)

# Search API — Dashboard

Source: [`modules/Search/Routes/api.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Search/Routes/api.php).

> **Verification:** HTTP methods, paths, route-level authentication and route comments are confirmed from source. Exact request and response schemas are **not verified** unless explicitly described. Do not treat illustrative placeholders as real API payloads.

Endpoints in this file: **1**.

## `GET /api/search/analytics`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** search.analytics
- **Path parameters:** None
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** No body expected for GET.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.
