import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "zudoku/ui/Card";
import { Button } from "zudoku/ui/Button";

## Bappy API

This document describes the **Bappy API** and the Bappy reseller platform: what it is, who it is for, and what it can do. It is intended for partners, resellers, and integrators as public documentation.

<div className="not-prose my-4">
  <Card>
    <CardContent className="pt-6">
      <div className="flex flex-wrap items-center gap-3">
        <Button asChild>
          <a href="/api/bundle-sim">View API Documentation →</a>
        </Button>
        <span className="text-sm text-muted-foreground">Interactive reference, request/response schemas, and examples</span>
      </div>
      <p className="mt-3 text-sm text-muted-foreground">
        Use the <strong>Interactive Playground</strong> on the API reference page to test endpoints with your Console <code>client_id</code> and <code>client_secret</code>.
      </p>
    </CardContent>
  </Card>
</div>

---

## 1. What is Bappy?

**Bappy** is a **multi-tenant API platform** that lets **resellers and partners** sell and manage **eSIM and physical SIM** data plans through a unified concept called **Links**. A **Link** represents a single card — whether eSIM or physical SIM — identified by a **UUID** or **ICCID**. Partners integrate via a single REST API to:

- Create new Links (activate eSIMs or physical SIMs)
- Top up existing Links with additional data plans
- Check Link status, usage, and network info
- View Link transaction history
- Send SMS to Links
- Manage plans, coverage, and regions
- View organization balance, transactions, and analytics

The platform handles authentication, billing (wallet/balance), provisioning with the mobile operator, and exposes a **unified, provider-agnostic** API. Partners do not need to integrate directly with the underlying operator; Bappy abstracts that.

---

## 2. Who is it for?

- **Resellers** — Sell eSIM or physical SIM plans to end customers (travel, M2M, etc.).
- **Integrators** — Embed Link creation and topup into your app, portal, or booking flow.
- **M2M / IoT** — Create and manage Links programmatically (machine-to-machine tokens supported).

Each partner is an **organization** (tenant). All data — Links, activations, topups, balance, transactions — is scoped to that organization. Access is controlled via **OmaxTelecom ID** (identity provider): OAuth 2.0 Client Credentials.

---

## 3. Core concept: Links

A **Link** is the central resource in Bappy. It represents a single card (eSIM or physical SIM) and all its associated data.

| Property | Description |
|----------|-------------|
| **UUID** | Unique identifier assigned on creation |
| **ICCID** | SIM card identifier (assigned by provider) |
| **Identifier** | All Link endpoints accept either **UUID** or **ICCID** as `{identifier}` |
| **Status** | `active`, `suspended`, or `inactive` |
| **Activations** | One or more plans attached to the Link (each with its own usage, expiry, coverage) |

### Examples:
- `GET /links/550e8400-e29b-41d4-a716-446655440000` (by UUID)
- `GET /links/8901010000000000001` (by ICCID)

---

## 4. Platform capabilities (what you can do)

### 4.1 Create a Link

- **Create Link** — `POST /links` with `plan_id` (and optional `name`). Balance is debited; the eSIM is provisioned. Returns Link UUID, ICCID, MSISDN, LPA profile, activation URL, and amount charged.

**Flow:**
1. Checks wallet balance (must cover plan's retail price)
2. Fetches available eSIM ICCID from provider
3. Deducts plan retail price from wallet
4. Creates provider endpoint with the plan
5. Creates Link + activation + transaction records
6. On provider failure: wallet amount is automatically refunded

### 4.2 View and manage Links

- **List Links** — `GET /links` with optional filters: `status`, `search`, `per_page`, `page`. Returns paginated list of all Links for your organization.
- **Get Link** — `GET /links/{identifier}` returns full Link details including: live usage data, eSIM activation URLs (Apple/Android), all activations with per-plan usage, and aggregated coverage data.
- **Reactivate Link** — `PUT /links/{identifier}` with `{"status": "active"}` to reactivate a suspended Link (synchronized with provider).

### 4.3 Plans and topup

- **Available topup plans** — `GET /links/{identifier}/topup-plans` returns plans compatible with a specific Link (filtered by matching sponsor profile). Each plan includes data amount, validity, pricing, and coverage summary.
- **Remove plan** — `PUT /links/{identifier}/plans` with `{"remove": ["activation-uuid"]}` to cancel an activation from a Link. Get the activation UUID from `GET /links/{identifier}` → `activations[].id`.

### 4.4 Link history

- **Transaction history** — `GET /links/{identifier}/history` returns a paginated list of all transactions for a Link: activations, topups, refunds, and monthly link fees. Ordered by date (newest first).

### 4.5 Network status

- **Live network status** — `GET /links/{identifier}/network-status?live=true` forces a live check from the provider, bypassing cache.

### 4.6 eSIM-specific

- **LPA profile** — Returned on Link creation; used for eSIM activation.
- **Apple activation URL** — Universal deep link for iOS eSIM installation.
- **Android activation URL** — Universal deep link for Android eSIM installation.
- **Installation instructions** — `GET /info/instructions` returns step-by-step eSIM installation guides for iOS and Android.

### 4.7 SMS

- **Send SMS** — `POST /sms` with `link_id` (UUID or ICCID) and `message` (max 80 characters). SMS is queued for async delivery.
- **List SMS** — `GET /sms?link_id={identifier}` to list SMS messages for a specific Link.

### 4.8 Plans (reference data)

- **List plans** — `GET /plans` with optional filters: `region`, `coverage_type`, `sponsor_profile`. Returns all available plans with pricing, data amount, validity, and coverage summary.
- **Get plan** — `GET /plans/{plan_id}` returns detailed plan information.
- **Plan coverage** — `GET /plans/{plan_id}/coverage` returns full coverage details: all countries and their operators with network types.
- **Coverage regions** — `GET /plans/regions` returns all available regions (EU, AF, AS, LA, NA, OC) for filtering plans.

### 4.9 Organization (tenant)

- **Profile** — `GET /organization`: name, slug, status, pricing settings (`price_per_sms`, `price_per_link`).
- **Balance** — `GET /organization/balance`: current wallet balance and currency (used for Link creation and topups).

### 4.10 Transactions and analytics

- **List transactions** — `GET /transactions` with optional `link_id` filter. For per-Link history, prefer `GET /links/{identifier}/history`.
- **Statistics** — `GET /transactions/stats` with optional `from`/`to` date range.
- **Analytics** — `GET /transactions/analytics` with optional `period_days` (e.g. last 30 days).

### 4.11 Info

- **eSIM installation instructions** — `GET /info/instructions` returns step-by-step guides for iOS and Android.
- **Mobile operators** — `GET /info/operators?search={country}` searches operators by country name.

---

## 5. Technical specifications

### 5.1 API

- **Style:** REST, JSON request/response.
- **Base path:** `/v1` (e.g. `https://api.omaxtelecom.com/bappy/v1`).
- **Authentication:** OAuth 2.0 Client Credentials via **OmaxTelecom ID**. Send `Authorization: Bearer <access_token>`. Token is obtained from `POST https://api.omaxtelecom.com/auth/token`, not from Bappy.
- **Public endpoints (no auth):** `GET /health`, `GET /status` for availability and dependency checks.

### 5.2 Link identifiers

All single-resource Link endpoints accept either a **Link UUID** or an **ICCID** as the `{identifier}` path parameter. Use whichever is more convenient for your integration.

### 5.3 Response format

- **Success:** `{ "success": true, "data": { ... }, "meta": { "timestamp", "response_time_ms" } }`.
- **Paginated:** `data` contains `data` (array) and `meta` (current_page, last_page, per_page, total, from, to).
- **Error:** `{ "success": false, "error": { "code", "message", "details" }, "meta": { "timestamp" } }` with appropriate HTTP status (401, 402, 404, 422, 502, etc.).

### 5.4 Multi-tenancy

- Every authenticated request is bound to an **organization** (tenant) derived from the token.
- All Links, transactions, balance, and SMS are scoped to that organization. No cross-tenant access.

### 5.5 Provider abstraction

- The platform does **not** expose the underlying mobile operator or provider name in the public API.
- Errors are normalized to generic codes (e.g. `PROVISIONING_ERROR`, `PROVIDER_UNAVAILABLE`). Internal provider details are not returned to clients.

### 5.6 Error codes (summary)

| Code | Typical HTTP | Meaning |
|------|-------------|---------|
| `UNAUTHORIZED` | 401 | Missing or invalid Bearer token |
| `INSUFFICIENT_BALANCE` | 402 | Wallet balance too low |
| `ORG_SUSPENDED` | 403 | Organization is suspended |
| `NOT_FOUND` | 404 | Resource not found |
| `PLAN_NOT_FOUND` | 404 | Plan not found or not enabled for your org |
| `VALIDATION_ERROR` | 422 | Invalid request parameters |
| `INVALID_STATUS_CHANGE` | 422 | Status transition not allowed |
| `INVALID_STATE` | 422 | Resource in invalid state |
| `INVALID_PLAN` | 422 | Plan not available for operation |
| `CONFIG_ERROR` | 500 | Server misconfiguration |
| `PROVISIONING_ERROR` | 502 | Provider API error |
| `PROVISIONING_FAILED` | 502 | Provider returned no result |
| `PROVIDER_ERROR` | 502 | Provider operation failed |

---

## 6. Getting started (high-level)

1. **Obtain credentials** — Get an organization (tenant) and OmaxTelecom ID credentials (`client_id` + `client_secret`).
2. **Get a token** — `POST https://api.omaxtelecom.com/auth/token` with Client Credentials grant. Use the returned `access_token` as `Authorization: Bearer <access_token>`.
3. **Discover plans** — `GET /plans` to see available packages with pricing, data, validity, and coverage.
4. **Check balance** — `GET /organization/balance` before creating or topping up Links.
5. **Create a Link** — `POST /links` with `plan_id` to create a new Link (eSIM activation). You'll receive UUID, ICCID, LPA profile, and activation URLs.
6. **Manage Links** — Use `GET /links` to list all Links, `GET /links/{identifier}` for details, and `GET /links/{identifier}/topup-plans` to find compatible topup plans.
7. **Optional:** Use **transactions** and **analytics** for reporting, and **SMS** for messaging.

---

## 7. Summary table

| Area | Capability |
|------|------------|
| **Links** | Central resource: represents eSIM or physical SIM, identified by UUID or ICCID |
| **Create Link** | Single eSIM activation with plan |
| **Topup** | Per Link with compatible topup plans |
| **Link Details** | Full details: usage, activations, eSIM URLs, coverage |
| **History** | Per-Link transaction history (activations, topups, refunds, fees) |
| **Network** | Live network status per Link |
| **SMS** | Send and list SMS per Link |
| **Plans** | List, filter by region/coverage/sponsor, view full coverage and operators |
| **Organization** | Profile, balance, pricing settings |
| **Transactions** | List, statistics, and analytics |
| **Info** | eSIM installation instructions, mobile operator search |
| **Auth** | OmaxTelecom ID (Client Credentials), Bearer token |
| **Billing** | Wallet balance per organization; debited on Link creation/topup |

---

## API Documentation

<div className="not-prose my-6">
  <Card>
    <CardHeader>
      <CardTitle>Complete API Reference</CardTitle>
      <CardDescription>
        Explore the full API documentation with interactive examples, request/response schemas, and authentication details.
      </CardDescription>
    </CardHeader>
    <CardContent>
      <Button asChild>
        <a href="/api/bundle-sim">View API Documentation →</a>
      </Button>
    </CardContent>
  </Card>
</div>

## Need Help?

If you have any questions or need assistance with the Bappy API, please contact our support team at [support@omaxtelecom.com](mailto:support@omaxtelecom.com).
