# 01 - Big Picture: M1.1 Tenant Registration Flow

Welcome to the learning guide for **Milestone 1, Step 1.1** of the Universal Chatbot Widget backend! 

Is document me hum pure M1.1 flow ko high level (badi tasveer) me samjhenge: **Client se leke MongoDB tak request kaise travel karti hai.**

---

## 1. What problem does M1.1 solve? (The "WHY")

Hum ek **Universal Chatbot Widget** bana rahe hain jo kisi bhi website (jaise Shopify store, WordPress blog, ya React web app) par drop kiya ja sakta hai.

Lekin har website ek alag client / customer hai. Isse hum **Multi-Tenancy** kehte hain:
- Ek website = Ek **Tenant**.
- Har Tenant ka ek unique **`siteId`** hota hai (jaise `site_8f3a1b9c4d2e`).

Is Milestone 1.1 ka goal hai: **Website owner apni website register kar sake aur system unhe ek unique `siteId` allocate karke MongoDB me store kar de.**

---

## 2. High-Level Flow Diagram

Jab koi website owner API par registration request bhejta hai, toh flow aisa hota hai:

```text
  [Client / Swagger UI / cURL]
             │
             │  HTTP POST /api/v1/tenant/register (JSON Payload)
             ▼
  ┌───────────────────────────────────────────────────────────┐
  │ 1. FastAPI Router (app/routers/tenant.py)                │
  │    - Request receive karta hai                            │
  └──────────────────────────┬────────────────────────────────┘
                             │
                             ▼
  ┌───────────────────────────────────────────────────────────┐
  │ 2. Pydantic Validation (app/models/tenant.py)            │
  │    - Check karta hai ki JSON structure sahi hai ya nahi  │
  │    - Domain ko clean/normalize karta hai (e.g. lowercase) │
  └──────────────────────────┬────────────────────────────────┘
                             │
                             ▼
  ┌───────────────────────────────────────────────────────────┐
  │ 3. Tenant Repository (app/repositories/tenant_repository.py)│
  │    - Check karta hai domain already exist karta hai ya nahi│
  │    - Unique siteId generate karta hai (uuid)             │
  │    - Data document structure prepare karta hai            │
  └──────────────────────────┬────────────────────────────────┘
                             │
                             ▼
  ┌───────────────────────────────────────────────────────────┐
  │ 4. MongoDB Database (app/database.py & AsyncMongoClient)  │
  │    - Async connection ke zariye document ko store karta hai│
  │    - Database: chatbot_db | Collection: tenants          │
  └──────────────────────────┬────────────────────────────────┘
                             │
                             ▼
  [Response: HTTP 201 Created with siteId & tenant details]
```

---

## 3. Step-by-Step Breakdown (In Simple Language)

### Step 1: Client Request
Client (jaise Postman, Swagger UI, ya terminal cURL) ek HTTP `POST` request bhejta hai URL `/api/v1/tenant/register` par.
Payload me do fields hoti hain:
- `domain`: Website ka address (e.g. `myawesomestore.com`)
- `name`: Website ka display name (e.g. `My Awesome Store`)

### Step 2: FastAPI Router Layer
FastAPI request ko decode karke `/api/v1/tenant/register` route handler function ko handover kar deta hai. Router decide karta hai ki is endpoint par kaunsa logic chalega.

### Step 3: Pydantic Validation & Normalization
Incoming raw JSON turant Python model `TenantCreate` me convert hota hai:
- Standard validation check hoti hai (jaise `name` empty na ho).
- `field_validator` domain se `http://` ya `https://` hata kar clean domain string banata hai (`myawesomestore.com`).
- Agar validation fail hoti hai, FastAPI directly `422 Unprocessable Entity` response bhej deta hai.

### Step 4: Repository (Database Abstraction) Layer
Directly route handler se database call karne ki jagah, hum **Repository Pattern** use karte hain:
- Repository function pehle MongoDB me search karti hai: *Kya ye domain pehle se registered hai?*
- Agar registered hai, toh `400 Bad Request` error returning function call handle karti hai.
- Agar new domain hai, toh function unique `siteId` generate karti hai (e.g. `site_a1b2c3d4e5f6`) aur `createdAt` timestamp add karti hai.

### Step 5: MongoDB Atlas / Local Database Write
PyMongo ka `AsyncMongoClient` connection setup use hota hai. Tenant document asymmetry bina application stream ko block kiye MongoDB database (`chatbot_db`) ki `tenants` collection me insert ho jata hai.

### Step 6: Response Return
Database me save hone ke baad API HTTP `201 Created` code ke sath `TenantResponse` model me formatted JSON client ko vapas bhejti hai. Client ko unka freshly generated `siteId` mil jata hai!

---

## Key Takeaway for Beginners
**Separation of Concerns:** Client se Database tak har layer ki ek specific job hai:
- Router = Traffic control (Endpoints)
- Pydantic = Quality check (Validation)
- Repository = Business logic & DB queries
- Database module = Connection management
