# Secudox API Documentation — Android Integration

Audience: Android client developers
Last updated: 2026-08-25

## 1. Overview

Secudox is a lost & found platform (items, missing persons, sightings, claims, rewards).
The Android app consumes the same REST API used by the web app.

**Key concepts**

| Concept | Description |
|---|---|
| Items | Lost/found reports posted by users. New posts go to **admin moderation** (`status: pending`) before becoming publicly visible (`active`). |
| Sightings | Reports that someone *found/spotted* a listed item. Created as `unverified`, then **verified by an admin**. |
| Missing persons | Posted as an `item` + `person_details` record. Sighting reports on people also start as `unverified` until admin verification. |
| Claims | A user claims a found item; may upload proof documents/images. Claims can be disputed. |
| Moderation queue | Admin-side review of new items. Not user-facing. |

## 2. Base URL & Conventions

```
Base URL: https://<deployment-domain>/api
Content-Type: application/json (except file uploads: multipart/form-data)
```

**Response envelope** — every endpoint returns:

```json
// success
{ "success": true, "data": { ... } }

// error
{ "success": false, "error": { "message": "..." } }
```

Common status codes: `200` OK, `201` Created, `400` Bad request, `401` Unauthorized (no/invalid token), `403` Forbidden (not owner/admin), `404` Not found, `500` Server error.

## 3. Authentication

Auth is handled by **Supabase Auth**. The Android app should use the Supabase Kotlin SDK (`io.github.jan-tennert.supabase`) or call Supabase Auth endpoints directly — do not build custom login screens against this API.

- Sign up / Sign in: Supabase email+password (and Apple sign-in is in use).
- Email confirmation: web flow via `/api/auth/confirm-signup` and `/api/auth/callback` (browser-based; deep-link back into the app).
- Every authenticated API call below requires the user's JWT:

```
Authorization: Bearer <supabase_access_token>
apikey: <NEXT_PUBLIC_SUPABASE_ANON_KEY>   (when calling Supabase directly)
```

Password change is available at `PATCH /api/users/{id}/password`.

## 4. Endpoints

### 4.1 Categories — `GET /api/categories`
Public. No params. Returns item categories (id, name).

### 4.2 Locations — `GET /api/locations`
Public. Returns known locations (id, label, city, latitude, longitude).

### 4.3 Items

#### `GET /api/items` — list/search items
Query params (all optional):

| Param | Notes |
|---|---|
| `type` | `lost` or `found` |
| `category_id` | filter by category UUID |
| `category_name` | filter by category name |
| `not_category_name` | exclude a category (used internally for Missing People) |
| `city` | location city |
| `query` | free-text search on title/description |
| `user_id` | items of a specific user (public profile view) |
| `page`, `limit` | pagination; limit max 50, default 12 |
| `sort` | default `created_at` |

Returns paginated `{ data: [...], count }`. Each item includes nested `category`, `location`, `images`.
Pending items are visible to their owner only.

#### `POST /api/items` — report a lost/found item *(auth required)*
```json
{
  "title": "Black backpack",          // required
  "type": "lost",                      // required: "lost" | "found"
  "categoryId": "<uuid>",              // required
  "description": "...",                // required
  "dateOccurred": "2026-08-20",        // required (ISO date)
  "locationLabel": "CBD, Nairobi",     // optional — creates a location record
  "latitude": -1.286,                  // optional
  "longitude": 36.817,                 // optional
  "rewardAmount": 500,                 // optional (KES)
  "paymentMethod": "card" | "mpesa",   // optional
  "payerPhone": "+2547..."             // optional
}
```
→ `201`. Item is created with `status: "pending"` and queued for admin moderation.
Owner sees it as *pending*; public sees it only after approval.

#### `GET /api/items/{id}` — item detail (with images)
#### `PATCH /api/items/{id}` — update *(owner or admin)*
Body: any of `title`, `description`, `status`, `rewardAmount`, `categoryId`, `dateOccurred`.
#### `DELETE /api/items/{id}` — delete *(owner or admin)*

#### `POST /api/items/{id}/images` — upload images *(auth)*
`multipart/form-data`, field `files` (repeatable). First image becomes primary.
→ `201 { data: ["<public url>", ...] }`.

### 4.4 Sightings — "I found/spotted this"

#### `GET /api/sightings?item_id=<uuid>&page=&limit=`
Sightings for one item.

#### `POST /api/sightings` *(auth required)*
```json
{
  "itemId": "<uuid>",            // required
  "locationLabel": "...",
  "latitude": ..., "longitude": ...,
  "sightedAt": "2026-08-24T10:00:00Z",
  "description": "...",
  "reporterPhone": "+2547..."
}
```
→ `201`, created with `status: "unverified"` — goes to admins for verification.

### 4.5 Missing Persons

#### `GET /api/missing-persons`
Filters: `status`, `query`, `city`, `is_child` (`true`/`false`), `page`, `limit` (max 50).
Child cases are flagged (`child_case` / `adult_case`) in admin views and prioritised for safety review.

#### `POST /api/missing-persons` *(auth required)*
Required: `fullName`, `description`, `dateOccurred`.
Optional: `age`, `gender`, `heightCm`, `weightKg`, `eyeColor`, `hairColor`, `skinTone`,
`clothingLastSeen`, `distinguishingFeatures`, `medicalConditions`, `isChild`,
`lastSeenAt`, `locationLabel`, `latitude`, `longitude`, `contactPhone`, `contactEmail`.
→ Creates an item (Missing People category) + `person_details` record.

#### `GET /api/missing-persons/{id}` — detail with images.

### 4.6 Claims

| Endpoint | Method | Notes |
|---|---|---|
| `/api/claims?status=` | GET | current user's claims; paginated |
| `/api/claims` | POST | body: `{ "itemId": "<uuid>", "description": "..." }` → starts as `submitted` |
| `/api/claims/{id}` | GET / PATCH / DELETE | claim lifecycle: `submitted → under_review → approved/rejected/disputed` |
| `/api/claims/{id}/proofs` | POST | proof upload (multipart) |

Claim statuses: `submitted`, `under_review`, `approved`, `rejected`, `disputed`.

### 4.7 Disputes

| Endpoint | Method | Body |
|---|---|---|
| `/api/disputes` | GET | current user's disputes |
| `/api/disputes` | POST | `{ "claimId": "<uuid>", "reason": "..." }` |
| `/api/disputes/{id}` | PATCH | update own dispute |

Dispute statuses: `open`, `under_review`, `resolved`, `closed`.

### 4.8 Notifications

| Endpoint | Method | Notes |
|---|---|---|
| `/api/notifications?unread_only=true&limit=` | GET | list (max 50) |
| `/api/notifications/unread-count` | GET | badge count |
| `/api/notifications/{id}` | PATCH | mark read |
| `/api/notifications/read-all` | PATCH | mark all read |

### 4.9 Push tokens — FCM registration

| Endpoint | Method | Body / Params |
|---|---|---|
| `/api/push-tokens` | POST | `{ "token": "<fcm-token>", "platform": "android" }` |
| `/api/push-tokens?token=` | DELETE | unregister a token |

Register after login and whenever FCM rotates the token.

### 4.10 Location subscriptions — proximity alerts

| Endpoint | Method | Body / Params |
|---|---|---|
| `/api/location-subscriptions` | GET | current user's subscriptions |
| `/api/location-subscriptions` | POST | `{ "latitude": .., "longitude": .., "radiusKm": .., "label": ".." }` |
| `/api/location-subscriptions?id=` | DELETE | remove subscription |

Users get notified when items are reported near a subscribed area.

### 4.11 Users / Profile

| Endpoint | Method | Notes |
|---|---|---|
| `/api/users/{id}` | GET / PATCH | profile read/update |
| `/api/users/{id}/avatar` | POST | multipart avatar upload |
| `/api/users/{id}/password` | PATCH | change password |
| `/api/users/{id}/items` | GET | user's items |
| `/api/users/{id}/deletion-request` | POST | GDPR-style account deletion request (requires the `deletion_requests` migration — see `supabase/migrations/20250601000000_deletion_requests.sql`) |

### 4.12 Contact — `POST /api/contact`
Body: `{ "name", "email", "subject", "message" }` — all required. No auth needed.

## 5. Typical Flows

### Report a lost item
1. `GET /api/categories` → pick category
2. `POST /api/items` (status = `pending`)
3. `POST /api/items/{id}/images` (optional photos)
4. Admin approves → item becomes publicly visible (`active`)
5. Another user finds it → `POST /api/sightings` (`unverified`)
6. Finder claims it → `POST /api/claims`; owner approves or disputes

### Report a missing person
1. `POST /api/missing-persons` (with details + last seen location)
2. Community submits sighting reports (`unverified`)
3. Admin verifies sightings → reporter/owner notified

## 6. Pending Backend Migrations (⚠️)

Two migrations have **not been applied** to production yet. Until they run:
- `POST /api/users/{id}/deletion-request` will fail (table missing).
- Child-safety reporting endpoints will fail (`reports` table missing).

See `supabase/migrations/` for the full schema history, or run `npm run db:migrate` to emit it for the Supabase SQL editor.

---

## 7. New Features (2026-08) — Trust, Payments, Matching

### 7.1 Two-way reporting — `POST /api/reports` *(auth)*
```json
{ "targetType": "item|user|claim|sighting", "targetId": "<id>", "reason": "csae|abuse|harassment|spam|fake|other", "description": "..." }
```
→ `201`. Reports land in the admin queue.

### 7.2 Ratings
- `POST /api/ratings` *(auth)* — `{ "itemId", "rateeId", "score": 1-5, "role": "owner"|"finder", "comment" }`. Only owner↔finder of an item can rate each other.
- `GET /api/users/{id}/ratings?page=&limit=` → list + `summary.averageScore`.

### 7.3 Identity verification (KYC)
- `GET /api/identity-verification` *(auth)* — current status + rejection reason.
- `POST /api/identity-verification` *(auth)* — `multipart/form-data`: `idType` (`national_id|passport|drivers_license`), `fullName`, `idNumber`, `dateOfBirth?`, `document` (file), `selfie?` (file).
- Admin review: `PATCH /api/admin/identity-verifications/{id}` with `{ action: "approve"|"reject", reason?, payoutRecipientCode? }`.

### 7.4 Reward payments (Paystack escrow)
Flow: owner funds reward → Secudox holds it → item returned & verified by admin → admin releases → finder paid after identity verification.

| Endpoint | Method | Notes |
|---|---|---|
| `/api/payments/initialize` | POST *(owner)* | `{ itemId, email }` → returns `checkoutUrl` (Paystack hosted checkout) + `accessCode` |
| `/api/payments/webhook` | POST | Paystack webhook (signature-verified); marks payment `funded`. Configure in Paystack dashboard. |
| `/api/payments/{reference}` | GET | status lookup (via items detail or add if needed) |
| `/api/admin/payments/{id}` | PATCH *(admin)* | `{ action: "release", finderId? }` or `{ action: "refund", reason? }` |

Payment statuses: `initialized → funded (held) → released` / `refunded` / `failed`.
Payouts require the finder's KYC to be approved (Paystack recipient code stored in KYC record).

### 7.5 Smart matching — `GET /api/items/{id}/matches`
Computes lost↔found matches for an active item. Scoring (0–100): text similarity 40 + location proximity within 25 km 35 + date proximity within ±14 days 25. Matches ≥30 are returned and persisted as suggestions; owners get a notification.
Response items include `matchedItemId`, `score`, `breakdown`, `lostItemId`, `foundItemId`.

### 7.6 Expiry & search
- Items auto-expire 30 days after creation (`expires_at`). Cron: `POST /api/cron/expire-items` with header `Authorization: Bearer <CRON_SECRET>` (wire to a daily scheduler).
- `GET /api/items?query=` now uses full-text search (`search_vector`, websearch syntax). `expires_soon=true` filters items expiring within 7 days.

### 7.7 Required environment variables
```
PAYSTACK_SECRET_KEY=sk_...
CRON_SECRET=<random-string>
```

### 7.8 Pending migration
Run `supabase/migrations/20260825000000_trust_payments_search.sql` in the Supabase SQL editor (adds `ratings`, `identity_verifications`, `payments`, `item_matches`, `items.expires_at`, `items.search_vector`).
