# Prompt: integrate Unwaani addresses into this project

Copy everything below the line into your AI coding assistant (Claude Code, Cursor, Copilot or similar) while it has your project open. It works for any stack. The assistant inspects your code first and asks before it guesses.

---

You are adding **Unwaani** to this project. Unwaani lets a customer pick a saved delivery address (map pin, building and entrance photos, floor, apartment, delivery notes) at checkout. Our server then receives the structured address and can send it to couriers as a link or a QR code. The full spec is at https://unwaani.com/developers/integration-guide.md. Fetch and read it before you write any code. If you can't fetch it, use the facts below. They are complete enough to build from.

## Facts (do not change them)

**Hosts**
- Web: `https://unwaani.com`
- API base: `https://api.unwaani.com/api/v1`
- JSON in and out. Errors look like `{"error": {"code", "message", "fields"?}}`.

**Credentials.** Read all three from environment variables, never hard-code them:
- `UNWAANI_CLIENT_ID` (`uwc_…`): public, safe to use in the browser.
- `UNWAANI_CLIENT_SECRET` (`uwsk_…`): **server only**. It must never reach a browser bundle, a mobile app, logs or Git.
- `UNWAANI_WEBHOOK_SECRET` (`whsec_…`): server only.
- `UNWAANI_REDIRECT_URI`: must exactly match a redirect URI registered in the Unwaani dashboard.

**Front end**
- Load `<script src="https://unwaani.com/sdk/v1/unwaani.js"></script>`, which defines the global `Unwaani`. The type definitions are at `https://unwaani.com/sdk/v1/unwaani.d.ts`.
- `Unwaani.button(elementOrSelector, {clientId, redirectUri, lang?, onSuccess({code, state}), onError(err)})`, or `await Unwaani.connect({clientId, redirectUri, mode?: "auto" | "popup" | "redirect"})`, which resolves to `{code, state}`.
- On desktop it opens a popup and resolves. On phones it redirects to `redirectUri?code=…&state=…`, or `?error=access_denied&state=…` if the customer cancels. On that page, `Unwaani.handleRedirect()` returns `{code, state}` and checks `state`, or throws.
- `err.code` is one of `closed`, `access_denied` or `state_mismatch`. Closing the popup is not an error worth showing.
- Without the SDK, link to `https://unwaani.com/connect?client_id=…&redirect_uri=…&state=<random>&lang=ar`, then check `state` on return.

**Server, all with `Authorization: Bearer $UNWAANI_CLIENT_SECRET`**
- `POST /partner/exchange?lang=en` with body `{code, redirect_uri, code_verifier?}` returns a **Grant**. The code works once and lasts 10 minutes; a bad one returns `400 invalid_code`.
- `GET /partner/grants/{grant_id}?lang=` returns the Grant with the current address. `410 grant_revoked` means the customer turned off sharing: ask them to connect again.
- `POST /partner/grants/{grant_id}/revoke` returns `204`. Use it when our customer deletes their account with us.
- `POST /partner/grants/{grant_id}/driver-links` with body `{order_ref?, expiry: "on_delivery" | "24h" | "7d", lang?}` returns a DriverLink: `{id, url, qr_svg_url, qr_png_url, message, status, arrived_at, delivered_at}`.
- `GET /partner/driver-links/{id}` and `POST /partner/driver-links/{id}/close`.
- The rate limit is 600 requests per minute. A 429 includes `Retry-After`.

**Grant**

```json
{ "id": "uuid", "status": "active|revoked", "customer": {"display_name", "phone"},
  "address": { "place_id", "kind", "kind_text", "location": {"lat", "lng"}, "maps_url", "waze_url",
    "address": {"area", "street", "building", "city", "country"}, "written_address",
    "entrance": {"code", "name", "text"}, "floor", "floor_text", "apartment", "landmark",
    "delivery": {"where", "where_text", "alerts", "alerts_text", "note", "voice_note_url"},
    "national_address_code", "contact_phone", "photos": [{"url", "thumb_url", "kind"}], "instructions" } }
```

Photo and voice URLs are signed and expire. Store `grant.id`, not those URLs.

**Webhooks**
- Unwaani sends `POST` to our webhook URL with body `{id, type, created_at, data}`.
- Verify the `Unwaani-Signature: t=<unix>,v1=<hex>` header on the **raw body**: `v1` = hex(HMAC_SHA256(webhook_secret, "<t>.<raw body>")). Use a constant-time compare, and reject when |now − t| > 300 s.
- Answer 2xx within 5 s and do the work after. Deduplicate by `id`, because retries happen.
- Event types:
  - `grant.created` and `grant.updated`: `data.grant`, with the full address.
  - `grant.revoked`: `data.grant_id` and `data.reason`. Delete the stored address and mark the customer as not connected.
  - `delivery.arrived` and `delivery.completed`: `data.driver_link_id`, `grant_id`, `order_ref` and `has_delivery_photo`.
  - `ping`.

## What to build

1. **Inspect first.** Find the framework, the checkout or address form, the customer and order models, how secrets and env vars are configured, the HTTP client already used, how background jobs run, and the test setup. Follow the project's existing conventions and libraries; don't add a new HTTP client or framework when one exists.
2. **Config.** Add the four env vars above to the project's config and `.env.example` (empty values) and document them.
3. **Unwaani client module** (server). A small typed wrapper for exchange, get grant, revoke, create, get and close driver link. It should:
   - add the bearer secret and a timeout of 10 s or less
   - map error codes to exceptions or results the app can act on (`invalid_code`, `grant_revoked`, `invalid_client`, `rate_limited`)
   - retry only safe GETs and 5xx/429 errors
4. **Storage.** A migration that adds a nullable `unwaani_grant_id` to the customer (or saved-address) model. If the project stores addresses, map the Grant into its existing address fields:
   - `written_address` goes to the address line
   - `location` goes to lat/lng
   - `floor_text` and `apartment` go to their own fields
   - `instructions` goes to the delivery notes
   - add a `source = "unwaani"` marker
   
   Don't store photo URLs.
5. **Checkout UI.** Put the button ("Enter your address", or the existing button style) next to the current address form.
   - On success, send `code` to a new server endpoint. That endpoint calls exchange, saves the grant ID on the current customer and returns the mapped address, which pre-fills the form.
   - Keep the manual address form as a fallback.
   - Handle the redirect path on the `UNWAANI_REDIRECT_URI` page (or route).
6. **Later orders.** When a returning customer has `unwaani_grant_id`, fetch the current address with GET grant instead of using a stale copy. On `grant_revoked`, clear the ID and show the button again.
7. **Courier handoff.** Where the project dispatches an order (an admin order page, a packing slip, a courier integration), call create driver link with the order number as `order_ref`, then:
   - show `url` and the QR code (`qr_svg_url`) on the packing slip or label
   - send `message` to the courier if the project already messages couriers
8. **Webhook endpoint.**
   - Verify the signature on the raw body. Many frameworks parse JSON before you can read it, so configure raw-body access for this route.
   - Deduplicate by event `id`, then handle each type:
     - `grant.updated`: refresh the stored address.
     - `grant.revoked`: clear the grant and the stored copy.
     - `delivery.*`: update the order status if the project tracks it.
   - Exempt the route from CSRF and auth middleware, never from signature checks.
9. **Tests.** Cover:
   - webhook signature: valid, wrong secret, stale timestamp, tampered body
   - the exchange endpoint, with the Unwaani HTTP calls mocked
   - address mapping
   - `grant_revoked` handling
   
   Run the project's test and lint commands and make them pass.

## Rules

- Never send `UNWAANI_CLIENT_SECRET` to the client, and never log it or full addresses.
- Never put the code, address or phone number in a URL you build. Unwaani only puts the one-time `code` and `state` in the redirect.
- Use the address only for this customer's orders. Show the customer that the address came from Unwaani and that they can change it.
- Don't invent endpoints or fields that aren't listed here. If something you need is missing, say so in your summary instead of guessing.
- Ask me before:
  - changing the checkout's existing required fields
  - adding a database table, rather than a column
  - adding a new dependency

## When you finish

Reply with:
- the files you changed
- the env vars I must set
- the URLs to register in the Unwaani dashboard: the redirect URI and the webhook URL
- how to test it end to end in sandbox, where only the business owner's own Unwaani account can connect until the business is verified
- anything you could not do
