# 🚀 Super Simple Usage - Apex SaaS Framework

## ⚡ Minimal Example (2 Lines!)

```python
from apex import Apex

app = Apex().app

# That's it! Run with: uvicorn app:app --reload
```

**You now have:**
- ✅ Complete authentication (signup, login, forgot password)
- ✅ User management
- ✅ Organization management
- ✅ Role-based permissions
- ✅ Settings management
- ✅ PayPal payments
- ✅ Auto-created database tables
- ✅ Interactive API docs at `/docs`

---

## 📦 With Custom Models (3 Lines!)

**models.py:**
```python
from apex import User, Organization

# Use built-in models - that's it!
```

**app.py:**
```python
from apex import Apex
from models import User, Organization

app = Apex(models=[User, Organization]).app
```

---

## 🎨 With Configuration (Simple!)

```python
from apex import Apex, ApexConfig

config = ApexConfig(
    title="My SaaS App",
    auto_create_tables=True,
    enable_payments=True
)

app = Apex(config=config).app
```

---

## 🔧 Extend Models (Easy!)

```python
from apex import User, Organization
from sqlalchemy import Column, String, Integer

class MyUser(User):
    """Add custom fields to User"""
    __tablename__ = "users"
    
    # Add your custom fields
    department = Column(String(100))
    employee_id = Column(String(50))
    age = Column(Integer)

class MyOrganization(Organization):
    """Add custom fields to Organization"""
    __tablename__ = "organizations"
    
    industry = Column(String(100))
    company_size = Column(Integer)
```

**Use in app:**
```python
from apex import Apex
from models import MyUser, MyOrganization

app = Apex(models=[MyUser, MyOrganization]).app
```

---

## 🎯 Add Custom Endpoints (Super Easy!)

```python
from apex import Apex, auth_required
from apex import User

apex = Apex()
app = apex.app

@app.get("/api/custom")
@auth_required
async def custom_endpoint(user: User):
    """Automatically gets the authenticated user!"""
    return {
        "message": f"Hello {user.first_name}!",
        "email": user.email
    }
```

---

## 🎨 Fluent API Style

```python
from apex import Apex

app = (
    Apex()
    .with_auth()
    .with_users()
    .with_payments()
    .with_settings()
    .build()
)
```

---

## 🔐 Authentication Examples

### Signup
```bash
curl -X POST "http://localhost:8000/api/auth/signup" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!",
    "first_name": "John",
    "last_name": "Doe",
    "phone": "+1234567890",
    "country": "US",
    "organization_name": "My Company"
  }'
```

### Login
```bash
curl -X POST "http://localhost:8000/api/auth/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=user@example.com&password=SecurePass123!"
```

Returns:
```json
{
  "access_token": "eyJhbGc...",
  "token_type": "bearer"
}
```

### Use Token
```bash
curl -X GET "http://localhost:8000/api/users/me" \
  -H "Authorization: Bearer eyJhbGc..."
```

---

## 🎯 Complete Working Example

**Directory Structure:**
```
my_app/
├── .env
├── models.py
└── app.py
```

**.env:**
```bash
DATABASE_URL=postgresql+asyncpg://admin:password123@localhost:5432/myapp
SECRET_KEY=your-secret-key-here
```

**models.py:**
```python
from apex import User, Organization

# That's it! Use the built-in models
```

**app.py:**
```python
from apex import Apex
from models import User, Organization

app = Apex(
    title="My SaaS App",
    models=[User, Organization]
).app

# Add custom endpoint (optional)
@app.get("/")
def home():
    return {"message": "Welcome to my app!"}
```

**Run:**
```bash
# Install
pip install apex-saas-framework uvicorn

# Start database (Docker)
docker run --name db -e POSTGRES_DB=myapp \
  -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=password123 \
  -p 5432:5432 -d postgres:15

# Run app
uvicorn app:app --reload
```

**Visit:** http://localhost:8000/docs

---

## 🎨 Event Hooks (Advanced but Simple!)

```python
from apex import Apex, on
from apex import User

apex = Apex()
app = apex.app

@on("user:created")
async def send_welcome_email(user: User):
    """Automatically runs when a user signs up"""
    print(f"📧 Sending welcome email to {user.email}")
    # Add your email sending logic here

@on("user:login")
async def track_login(user: User):
    """Automatically runs on every login"""
    print(f"🔐 User {user.email} logged in")
    # Add analytics tracking here
```

---

## 🚀 Selective Features

Want only specific features? Easy!

```python
from apex import Apex

app = Apex(
    enable_auth=True,           # Authentication ✅
    enable_users=True,          # User management ✅
    enable_organizations=True,  # Organizations ✅
    enable_roles=False,         # Roles ❌
    enable_permissions=False,   # Permissions ❌
    enable_modules=True,        # Feature flags ✅
    enable_settings=True,       # Settings ✅
    enable_payments=False       # Payments ❌
).app
```

---

## 💡 What Gets Auto-Created

When you use `Apex()`, you automatically get these endpoints:

### Authentication
- `POST /api/auth/signup` - Sign up new user
- `POST /api/auth/login` - Login and get token
- `POST /api/auth/logout` - Logout
- `POST /api/auth/forgot-password` - Request password reset
- `POST /api/auth/reset-password` - Reset password with token
- `POST /api/auth/change-password` - Change password

### Users
- `GET /api/users/me` - Get current user
- `GET /api/users` - List users
- `GET /api/users/{id}` - Get user by ID
- `PUT /api/users/{id}` - Update user
- `DELETE /api/users/{id}` - Delete user

### Organizations
- `GET /api/organizations` - List organizations
- `GET /api/organizations/{id}` - Get organization
- `POST /api/organizations` - Create organization
- `PUT /api/organizations/{id}` - Update organization
- `DELETE /api/organizations/{id}` - Delete organization

### Roles & Permissions (if enabled)
- `GET /api/roles` - List roles
- `POST /api/roles` - Create role
- `GET /api/permissions` - List permissions
- `POST /api/permissions` - Create permission

### Settings
- `GET /api/settings/user` - Get user settings
- `PUT /api/settings/user` - Update user settings
- `GET /api/settings/organization` - Get org settings
- `PUT /api/settings/organization` - Update org settings

### Payments (PayPal - if enabled)
- `POST /api/payments/create-subscription` - Create subscription
- `POST /api/payments/cancel` - Cancel subscription
- `GET /api/payments/subscriptions/{id}` - Get subscription
- `POST /api/payments/webhook` - PayPal webhook

**Plus:**
- `GET /` - Root endpoint
- `GET /health` - Health check
- `GET /docs` - Interactive API documentation
- `GET /redoc` - ReDoc documentation

---

## 🎯 Comparison: Before vs After

### ❌ OLD WAY (Complex)
```python
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from pydantic import BaseModel, EmailStr
from apex.core.config import get_settings
from apex.core.security import get_password_hash, verify_password, create_access_token
from apex.infrastructure.database import get_session, get_engine
from apex.infrastructure.database.base import Base
# ... 20 more imports ...
# ... 100 lines of boilerplate code ...
```

### ✅ NEW WAY (Simple!)
```python
from apex import Apex

app = Apex().app
```

**That's it!** 🎉

---

## 📚 Import Patterns

```python
# Pattern 1: Absolute minimum
from apex import Apex
app = Apex().app

# Pattern 2: With models
from apex import Apex, User, Organization
app = Apex(models=[User, Organization]).app

# Pattern 3: With config
from apex import Apex, ApexConfig
config = ApexConfig(title="My App")
app = Apex(config=config).app

# Pattern 4: With decorators
from apex import Apex, auth_required, permission_required
app = Apex().app

@app.get("/custom")
@auth_required
async def custom(user):
    return {"user": user.email}

# Pattern 5: Everything you need
from apex import (
    Apex,
    User,
    Organization,
    auth_required,
    permission_required,
    on
)
```

---

## 🎉 Summary

**Old way:** 100+ lines of imports and boilerplate

**New way:** 2 lines of code

```python
from apex import Apex
app = Apex().app
```

**You get:**
- ✅ Authentication & Authorization
- ✅ User Management
- ✅ Organization Management
- ✅ RBAC (Roles & Permissions)
- ✅ Settings Management
- ✅ PayPal Integration
- ✅ Database Auto-Setup
- ✅ API Documentation
- ✅ Multi-tenant Support
- ✅ JWT Authentication
- ✅ Password Hashing
- ✅ Email Integration Ready

**All from 2 lines of code!** 🚀

---

## 🆘 Need Help?

- **Interactive Docs:** http://localhost:8000/docs (when running)
- **Full Guide:** `USER_GUIDE.md`
- **API Reference:** `API_REFERENCE.md`
- **Quick Start:** `QUICK_START.md`

---

**Welcome to the easiest SaaS framework in Python!** 🎉

