> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mypopup.shop/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture Overview

> High-level architecture of the Popup Store platform

## System Architecture

```mermaid theme={null}
graph TB
    Buyer[👤 Buyer] -->|Visits| Web[Web Store<br/>Next.js]
    Seller[👨‍💼 Seller] -->|Manages| iOS[iOS App<br/>Swift]

    Web -->|API Calls| Supabase[(Supabase)]
    iOS -->|API Calls| Supabase

    Supabase -->|Auth| Auth[Authentication]
    Supabase -->|Data| Postgres[(PostgreSQL)]
    Supabase -->|Files| Storage[Storage]
    Supabase -->|Functions| Edge[Edge Functions]

    Edge -->|Payments| Razorpay[Razorpay API]
    Edge -->|Emails| Resend[Resend API]
    Edge -->|AI| OpenAI[DALL-E 2]

    Web -->|Analytics| PostHog[PostHog]
    iOS -->|Push| OneSignal[OneSignal]

    style Web fill:#22c55e
    style iOS fill:#3b82f6
    style Supabase fill:#3ecf8e
```

## Component Breakdown

### 1. Web Store (Frontend)

<Card title="Next.js 14 Application" icon="browser" href="https://github.com/unfinished-bizness/getpopup-store">
  **Tech Stack:**

  * Next.js 14 (App Router)
  * TypeScript
  * Tailwind CSS + Radix UI
  * React Query (TanStack Query)

  **Key Features:**

  * Subdomain-based multi-tenancy
  * Server-side rendering (SSR) for SEO
  * Shopping cart and checkout flow
  * Payment method selection (UPI/Razorpay)
  * Order tracking pages
</Card>

### 2. iOS App (Seller Dashboard)

<Card title="Native iOS App" icon="mobile" href="https://github.com/unfinished-bizness/popupstore.ios">
  **Tech Stack:**

  * Swift 5.9
  * SwiftUI
  * Supabase Swift SDK
  * OneSignal (Push Notifications)

  **Key Features:**

  * Product CRUD with image upload
  * AI-powered product descriptions
  * Order management workflow
  * Analytics dashboard
  * Store customization
</Card>

### 3. Backend (Supabase)

<Card title="Supabase Platform" icon="database" href="https://github.com/unfinished-bizness/popup-supabase">
  **Services:**

  * PostgreSQL database
  * Row-Level Security (RLS) policies
  * Authentication (Email/OAuth)
  * Storage (product images)
  * Edge Functions (serverless)
  * Realtime subscriptions

  **Key Features:**

  * Multi-tenant data isolation
  * Email notifications
  * Payment processing
  * Order lifecycle management
</Card>

## Data Flow

### Product Creation Flow

```mermaid theme={null}
sequenceDiagram
    participant Seller
    participant iOS App
    participant Supabase
    participant OpenAI
    participant Storage

    Seller->>iOS App: Create Product
    iOS App->>OpenAI: Generate Description (AI)
    OpenAI-->>iOS App: Product Description
    iOS App->>OpenAI: Generate Image (DALL-E)
    OpenAI-->>iOS App: Product Image
    iOS App->>Storage: Upload Image
    Storage-->>iOS App: Image URL
    iOS App->>Supabase: Insert Product
    Supabase-->>iOS App: Product Created
    iOS App-->>Seller: Success ✅
```

### Order Placement Flow

```mermaid theme={null}
sequenceDiagram
    participant Buyer
    participant Web
    participant Supabase
    participant Razorpay
    participant Email
    participant Seller

    Buyer->>Web: Add to Cart
    Buyer->>Web: Proceed to Checkout
    Web->>Supabase: Create Order (pending)

    alt UPI Direct
        Web->>Buyer: Show QR Code
        Buyer->>Buyer: Pay via UPI App
        Buyer->>Web: Upload Payment Proof
        Web->>Supabase: Update Order (proof uploaded)
    else Razorpay
        Web->>Razorpay: Initialize Payment
        Razorpay->>Buyer: Payment Page
        Buyer->>Razorpay: Complete Payment
        Razorpay->>Supabase: Webhook (payment success)
    end

    Supabase->>Email: Send Confirmation Emails
    Email-->>Buyer: Order Confirmation
    Email-->>Seller: New Order Alert
    Seller->>iOS App: View New Order
```

## Multi-Tenancy Strategy

### Subdomain Routing

<Tabs>
  <Tab title="How it Works">
    Each seller gets a unique subdomain:

    ```
    shopname.mypopup.shop → Seller's Store
    another.mypopup.shop  → Different Store
    ```

    **Middleware Logic:**

    ```typescript theme={null}
    export function middleware(req: NextRequest) {
      const hostname = req.headers.get('host') || ''
      const subdomain = hostname.split('.')[0]

      // Fetch store data based on subdomain
      const store = await getStoreBySubdomain(subdomain)

      // Pass to page as context
      return NextResponse.rewrite(new URL(`/${store.id}`, req.url))
    }
    ```
  </Tab>

  <Tab title="Database Design">
    **Tables:**

    ```sql theme={null}
    stores
      - id (uuid)
      - subdomain (unique)
      - owner_id (user_id)
      - brand_color
      - logo_url

    products
      - id (uuid)
      - store_id (foreign key)
      - title, price, etc.

    orders
      - id (uuid)
      - store_id (foreign key)
      - buyer_email
      - status
    ```

    **RLS Policies:**

    ```sql theme={null}
    -- Sellers can only see their own store's data
    CREATE POLICY "Sellers view own products"
      ON products FOR SELECT
      USING (store_id IN (
        SELECT id FROM stores WHERE owner_id = auth.uid()
      ));
    ```
  </Tab>
</Tabs>

## Deployment Architecture

<CardGroup cols={2}>
  <Card title="Web App" icon="cloud">
    **Cloudflare Pages**

    * Edge network (global CDN)
    * Automatic SSL
    * Wildcard subdomain support
    * Zero config deployment
  </Card>

  <Card title="iOS App" icon="app-store-ios">
    **Apple App Store**

    * TestFlight for beta testing
    * Push notification certificates
    * In-app purchase ready (future)
  </Card>

  <Card title="Database" icon="database">
    **Supabase Cloud**

    * Managed PostgreSQL
    * Auto backups
    * Connection pooling (PgBouncer)
    * Global edge functions
  </Card>

  <Card title="Email" icon="envelope">
    **Resend**

    * React Email templates
    * High deliverability
    * Webhook events
    * Custom domain ready
  </Card>
</CardGroup>

## Security Considerations

<AccordionGroup>
  <Accordion title="Authentication">
    * Email/password with email verification
    * OAuth providers (Google, Apple, GitHub)
    * JWT tokens with refresh rotation
    * Row-level security (RLS) on all tables
  </Accordion>

  <Accordion title="Payment Security">
    * PCI-compliant via Razorpay
    * UPI payments with manual verification
    * No credit card data stored locally
    * Payment webhooks verified with signatures
  </Accordion>

  <Accordion title="Data Isolation">
    * Strict RLS policies per store
    * No cross-store data leakage
    * API keys in environment variables
    * Secrets in Supabase Vault
  </Accordion>

  <Accordion title="Rate Limiting">
    * Supabase built-in rate limits
    * Cloudflare DDoS protection
    * API key rotation strategy
    * Suspicious activity monitoring
  </Accordion>
</AccordionGroup>

## Performance Optimizations

1. **Web Store**
   * Static generation for public pages
   * Image optimization (Next.js Image)
   * React Query caching
   * Edge caching (Cloudflare)

2. **iOS App**
   * Image lazy loading
   * Pagination for large lists
   * Local caching (UserDefaults)
   * Background fetch for orders

3. **Database**
   * Indexed columns (store\_id, created\_at)
   * Materialized views for analytics
   * Connection pooling
   * Read replicas (future)

<Info>
  Want to dive deeper? Check out the [Database Schema](/architecture/database) or [Payment Flow](/architecture/payment-flow)
</Info>
