# Laravel API Refactor Plan (Mobile-first)

This plan hardens and standardizes the existing Laravel 12 API for Flutter mobile consumption while preserving current web functionality.

## 1) Response standardization

### 1.1 Introduce a central API response helper

- Add `app/Support/ApiResponse.php` (or similar) with helpers:
  - `success($data = null, $message = 'OK', $meta = [])`
  - `error($message, $statusCode = 400, $errors = null, $meta = [])`
  - `paginated(LengthAwarePaginator $paginator, $resourceCollection)`
  - Adds `meta.trace_id` (from request header or generated)

### 1.2 Ensure Resources are nested in envelope

Currently mixed patterns exist:
- some controllers return `{success,message,data,meta}`
- some return Resource responses directly

Mobile requirement: **every endpoint** returns the envelope (even when using `JsonResource`).

## 2) Exception & validation handling

- Update `app/Exceptions/Handler.php` to render JSON errors consistently for `/api/*` routes:
  - `ValidationException` → 422 envelope with `errors` field
  - `AuthenticationException` → 401 envelope
  - `AuthorizationException` → 403 envelope
  - `ModelNotFoundException` → 404 envelope
  - fallback → 500 envelope with safe message and `trace_id`

## 3) Auth lifecycle (Sanctum)

### 3.1 Keep OTP login, improve token endpoints

Existing:
- `POST /api/v1/auth/send-otp`
- `POST /api/v1/auth/verify-otp` returns token + user

Add:
- `GET /api/v1/me` (auth)
- `POST /api/v1/auth/logout` (auth) revokes current token

## 4) Modules API (type-safe)

### 4.1 Fix ambiguous module show

Current `ModuleController::show` searches across multiple tables by id.
This can return the wrong entity when ids overlap.

Add type-safe endpoints:
- `/api/v1/property/{id}`
- `/api/v1/jobs/{id}`
- `/api/v1/education/{id}`
- `/api/v1/services/{id}` (local_services)

Keep `/api/v1/modules` for lists (with pagination + filters).

### 4.2 Add filters incrementally (mobile-driven)

Start with:
- `q` (title/description)
- `sort` (`latest`, `price_low`, `price_high` where applicable)

Then per module:
- property: `purpose`, `area_id`, `pincode`, `bhk`, `furnishing`
- jobs: `segment`, `job_category_id`
- education: `study_level`
- service: `category_id`, `area_id`, `pincode` (lead capture)

## 5) Leads API

Standardize lead creation for:
- module enquiry (property/job/education/service)
- job application
- education enquiry

Recommended API additions:
- `GET /api/v1/me/leads` (auth)
- `POST /api/v1/jobs/apply` (auth)
- `POST /api/v1/education/enquire` (public, throttled)

## 6) Ads API

Existing:
- `GET /api/v1/ads`

Add:
- `POST /api/v1/ads/{id}/click` for app click tracking (do not use web route)

## 7) Payments / Quick Pay

Existing API `POST /api/v1/payments/razorpay/order` currently only creates a record via `PaymentService`.

Refactor to:
- create **real Razorpay order** (via `RazorpayService`)
- persist `razorpay_order_id`, amount, currency, receipt, customer fields
- expose `key_id` (public) and `order_id` for mobile checkout

Add:
- `POST /api/v1/payments/razorpay/verify` signature verification + status update
- `GET /api/v1/me/payments` payment history

## 8) Security hardening (do now)

- **Secrets**: remove default Razorpay key/secret values from `config/services.php` (env-only).
- **TLS**: remove `withoutVerifying()` from `RazorpayService` to enforce TLS verification.
- **Rate limiting**: align OTP + public forms throttle for API endpoints.

## 9) Query performance & payload reduction

- Always `select()` only needed columns in list endpoints.
- Use `with()` only when required.
- Use Resources/DTOs to shape minimal mobile payloads (list vs detail).
- Ensure indexes exist for commonly filtered columns: `status`, `service_id`, `job_category_id`, `study_level`, `(module_type,module_id,user_id)` for leads.

# Laravel API Refactor Plan (Mobile-First, Enterprise)

This plan is an implementation guide to evolve the current Laravel 12 API into a **stable, mobile-first, versioned API** matching `docs/mobile/API_CONTRACTS_V1.md`.

## 1) Standardize API responses

### 1.1 Introduce a response builder

Create a small helper (example location):
- `app/Support/ApiResponse.php`

Responsibilities:
- `success(data, message, meta=[])`
- `error(message, status=400, errors=null, meta=[])`
- `paginated(paginator, items, message, extraMeta=[])`
- automatically attach `trace_id` (use `request()->header('X-Request-Id')` fallback to `Str::uuid()`)

### 1.2 Centralize exception → JSON mapping (Laravel 12)

Laravel 12 handles exception rendering in `bootstrap/app.php` using `->withExceptions(...)`.

Add renderers for API requests (when `request()->is('api/*')` or `expectsJson()`):
- `ValidationException` → 422 with `errors` map
- `AuthenticationException` → 401
- `AuthorizationException` / `AccessDeniedHttpException` → 403
- `ModelNotFoundException` → 404
- `ThrottleRequestsException` → 429 with retry seconds (if available)
- fallback `Throwable` → 500 (log with trace_id; never leak stack in prod)

Goal: every API error matches the envelope.

## 2) Auth lifecycle (OTP + Sanctum)

Current:
- `POST /api/v1/auth/send-otp`
- `POST /api/v1/auth/verify-otp` returns `{token,user}` (good)

Add:
- `GET /api/v1/me` (auth:sanctum)
- `POST /api/v1/auth/logout` (auth:sanctum) — revoke current token

Hardening:
- enforce token abilities/scopes if needed later (`mobile-app` token name already used)
- ensure user resource is minimal + stable for mobile (do not expose permissions/admin fields to customer app unless required)

## 3) Module endpoints (avoid ambiguous lookups)

Problem:
- `ModuleController::show($module)` currently searches **multiple tables by id**; this is ambiguous if ids collide.

Solution:
- keep `GET /api/v1/modules?type=...` for list
- introduce **type-safe** endpoints:
  - `GET /api/v1/property/{id}`
  - `GET /api/v1/jobs/{id}`
  - `GET /api/v1/education/{id}`
  - `GET /api/v1/services/{id}` (local service listing)

Implementation notes:
- Introduce dedicated controllers:
  - `app/Http/Controllers/Api/PropertyController.php`, `JobController.php`, etc.
- Use API Resources per type:
  - `PropertyResource`, `JobResource`, `EducationResource`, `LocalServiceResource`
- Add query filters/pagination per type (module-by-module) using Request classes.

## 4) Leads API

Current:
- `POST /api/v1/leads` uses `StoreLeadRequest`
- `GET /api/v1/user/leads` exists

Improve:
- add `GET /api/v1/me/leads` (rename; keep old as alias for backward compatibility)
- update `LeadResource` to include mobile-relevant fields:
  - `module_type`, `module_id`, `lead_category`, `location`, `pincode` (if present), `updated_at`
- implement dedupe rules similar to web (optional): prevent duplicate module enquiries for same user/module.

Specialized lead endpoints:
- `POST /api/v1/jobs/apply` (auth)
- `POST /api/v1/education/enquire` (public, throttled)

## 5) Ads API + click tracking

Current:
- `GET /api/v1/ads` with `placement` filter

Add:
- `POST /api/v1/ads/{ad}/click`
  - store device/app source info (optional)
  - return `open_url` if needed

Use:
- Request validation: `StoreAdClickRequest`
- Service layer: `AdClickService`

## 6) Payments / Quick Pay (Razorpay)

Current API:
- `POST /api/v1/payments/razorpay/order` exists but only creates a `Payment` record (per `PaymentService`), while web Quick Pay uses Razorpay order + verify signature in `QuickPayController`.

Target:
- reuse the **web quick-pay proven flow** for mobile API:
  - `POST /api/v1/payments/razorpay/order` (auth) should:
    - validate request (`service_name, customer_name, mobile_number, amount`)
    - call `RazorpayService::createOrder`
    - persist `payments` row with `razorpay_order_id`, status pending/created
    - respond with `key_id` + `order_id` + amounts
  - `POST /api/v1/payments/razorpay/verify` (auth) should:
    - verify signature using `RazorpayService::verifySignature`
    - update payment record with success/failed + receipt number
  - `GET /api/v1/me/payments` (auth) list quick pay history

Security fixes (must-do for production):
- `config/services.php` currently defines default Razorpay key/secret values. Remove defaults and require env-only.
- `app/Services/RazorpayService.php` currently uses `->withoutVerifying()`; enable TLS verification for production.
- Ensure amounts are server-trusted (never trust client totals beyond validated numeric range).

## 7) Performance + payload reduction

- Use `select([...])` columns for list endpoints (avoid returning full meta/description when not needed).
- Eager-load only required relationships.
- Add indexes aligned with filters (`status`, `service_id`, `job_category_id`, `study_level`, etc.).
- Cache static reference lists where appropriate (e.g. service categories).

## 8) Versioning and deprecation policy

- Keep `/api/v1` stable for the mobile app.
- Any breaking change requires `/api/v2`.
- Old endpoints can remain as aliases with warnings in logs for a defined window.

