# Pokemon Card Resell Platform — Generated Backend

## Overview

This is a **FastAPI-based backend** for the **Pokemon Card Resell Platform**, a specialized e-commerce marketplace enabling collectors and traders to buy, sell, and trade Pokemon trading cards with secure transactions, card authentication, and inventory management.

The system supports multiple user roles (guest, buyer, seller, moderator, admin) and provides comprehensive functionality across 15 modules including user management, card catalog, listing management, order processing, payments, shipments, reviews, offers, disputes, and more.

**Key Features:**
- 35 entities with full CRUD operations
- Role-based access control
- Complex workflows (checkout, order fulfillment, dispute resolution)
- Batch write services for multi-entity operations
- Detailed eager-loading endpoints for optimized queries
- Comprehensive business rules and validation

**Technology Stack:**
- FastAPI (Python web framework)
- Pydantic (data validation)
- SQLAlchemy (ORM, ready for database integration)
- In-memory storage (development mode)

## Requirements

- **Python 3.8+**
- **uv** (fast Python package installer and runner)

## Install uv

Install `uv` using the official installation script:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or run:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

The project uses `uv` for dependency management. All dependencies are declared in `pyproject.toml`.

To install dependencies:

```bash
uv sync
```

This will create a virtual environment and install:
- `fastapi`
- `uvicorn[standard]`
- `pydantic`
- `python-multipart`

## Run the Backend

Start the FastAPI development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The server will start at **http://localhost:8000**

You should see output similar to:
```
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process
INFO:     Started server process
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```

## API Docs

FastAPI automatically generates interactive API documentation:

- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc

These interfaces allow you to:
- Browse all available endpoints
- View request/response schemas
- Test API calls directly from the browser
- Download OpenAPI specification

## OpenAPI JSON

The OpenAPI specification is available at:

**http://localhost:8000/openapi.json**

This JSON file can be imported into tools like Postman, Insomnia, or used to generate client SDKs.

## Project Files

```
pokemon-card-resell-platform/
├── main.py                 # FastAPI application entry point
├── pyproject.toml          # Project dependencies and metadata
├── README.md               # This file
└── .python-version         # Python version specification
```

**main.py** contains:
- All entity models (User, Listing, Order, etc.)
- Pydantic schemas for request/response validation
- CRUD endpoints for all 35 entities
- Custom workflow endpoints (register, checkout, ship, etc.)
- Detail endpoints with eager loading
- Batch write services
- In-memory data storage

## Example Workflow

### 1. Register a New User

```bash
curl -X POST http://localhost:8000/users/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "collector@example.com",
    "password": "SecurePass123",
    "role": "buyer"
  }'
```

**Response:**
```json
{
  "id": "usr_abc123",
  "email": "collector@example.com",
  "role": "buyer",
  "is_active": true,
  "is_verified": false,
  "created_at": "2024-01-15T10:30:00Z"
}
```

### 2. Create a Card Set

```bash
curl -X POST http://localhost:8000/card-sets \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Base Set",
    "series": "Original Series",
    "release_date": "1999-01-09",
    "total_cards": 102,
    "set_code": "BS"
  }'
```

### 3. Create a Card

```bash
curl -X POST http://localhost:8000/cards \
  -H "Content-Type: application/json" \
  -d '{
    "card_set_id": "set_xyz789",
    "name": "Charizard",
    "pokemon_name": "Charizard",
    "card_number": "4",
    "rarity": "Rare Holo",
    "card_type": "pokemon",
    "pokemon_type": "Fire",
    "hp": 120
  }'
```

### 4. Get Card Details

```bash
curl http://localhost:8000/cards/card_123
```

**Response:**
```json
{
  "id": "card_123",
  "card_set_id": "set_xyz789",
  "name": "Charizard",
  "pokemon_name": "Charizard",
  "card_number": "4",
  "rarity": "Rare Holo",
  "card_type": "pokemon",
  "pokemon_type": "Fire",
  "hp": 120,
  "created_at": "2024-01-15T10:35:00Z"
}
```

### 5. Create a Listing (Seller)

```bash
curl -X POST http://localhost:8000/listings \
  -H "Content-Type: application/json" \
  -d '{
    "seller_id": "usr_seller456",
    "card_id": "card_123",
    "title": "Charizard Base Set Holo - Near Mint",
    "description": "Beautiful condition, no scratches",
    "price": 299.99,
    "quantity": 1,
    "condition": "near_mint",
    "language": "English",
    "is_first_edition": false,
    "accepts_offers": true,
    "status": "active"
  }'
```

### 6. Search Listings

```bash
curl "http://localhost:8000/listings/search?card_name=Charizard&min_price=100&max_price=500"
```

### 7. Add to Cart

```bash
curl -X POST http://localhost:8000/cart-items \
  -H "Content-Type: application/json" \
  -d '{
    "cart_id": "cart_buyer789",
    "listing_id": "listing_abc123",
    "quantity": 1,
    "price_snapshot": 299.99
  }'
```

### 8. Checkout Cart

```bash
curl -X POST http://localhost:8000/carts/cart_buyer789/checkout \
  -H "Content-Type: application/json" \
  -d '{
    "shipping_address_id": "addr_ship123",
    "billing_address_id": "addr_bill123",
    "payment_method": "credit_card"
  }'
```

### 9. Get Order Details (with eager loading)

```bash
curl http://localhost:8000/orders/order_xyz456/details
```

**Response includes:**
- Order information
- Buyer and seller details
- Order items with card and listing information
- Payment status
- Shipment tracking
- Shipping and billing addresses

### 10. Mark Order as Shipped

```bash
curl -X POST http://localhost:8000/orders/order_xyz456/ship \
  -H "Content-Type: application/json" \
  -d '{
    "carrier": "USPS",
    "tracking_number": "9400111899562537289456",
    "shipping_method": "Priority Mail"
  }'
```

## Next Steps

This generated backend provides a solid foundation for the Pokemon Card Resell Platform. To move toward production, consider the following enhancements:

### 1. **Database Persistence**
   - Replace in-memory storage with PostgreSQL, MySQL, or SQLite
   - Implement SQLAlchemy models with proper relationships
   - Add database migrations using Alembic
   - Configure connection pooling and query optimization

### 2. **Authentication & Authorization**
   - Implement JWT-based authentication
   - Add OAuth2 password flow with token refresh
   - Create role-based access control (RBAC) middleware
   - Secure endpoints based on user roles (buyer, seller, moderator, admin)
   - Add API key authentication for external integrations

### 3. **Code Organization**
   - Split `main.py` into modular structure:
     - `models/` — SQLAlchemy ORM models
     - `schemas/` — Pydantic request/response schemas
     - `routers/` — API route handlers by module
     - `services/` — Business logic and batch operations
     - `repositories/` — Data access layer
     - `middleware/` — Authentication, logging, error handling
     - `config.py` — Environment configuration
     - `dependencies.py` — Shared dependencies (DB session, auth)

### 4. **Testing**
   - Add unit tests with `pytest`
   - Create integration tests for workflows
   - Implement test fixtures and factories
   - Add API endpoint tests using `TestClient`
   - Set up continuous integration (CI) pipeline
   - Aim for >80% code coverage

### 5. **Business Logic Implementation**
   - Implement all 18 business rules (email verification, commission calculation, etc.)
   - Add validation rules (password strength, price limits, etc.)
   - Create scheduled tasks for:
     - Auto-completing orders after 7 days
     - Expiring offers after 48 hours
     - Processing seller payouts
     - Sending price alert notifications

### 6. **External Integrations**
   - Payment gateway (Stripe, PayPal)
   - Email service (SendGrid, AWS SES)
   - Cloud storage for images (AWS S3, Cloudinary)
   - Shipping carrier APIs (USPS, FedEx, UPS)
   - SMS notifications (Twilio)

### 7. **Performance & Scalability**
   - Add Redis for caching frequently accessed data
   - Implement background job processing (Celery, RQ)
   - Add database indexing for search queries
   - Optimize N+1 query problems with eager loading
   - Implement rate limiting and request throttling

### 8. **Monitoring & Logging**
   - Add structured logging (JSON format)
   - Implement application monitoring (Sentry, DataDog)
   - Create health check endpoints
   - Add metrics collection (Prometheus)
   - Set up alerting for critical errors

### 9. **Security Enhancements**
   - Add input sanitization and XSS protection
   - Implement CORS policies
   - Add request validation and rate limiting
   - Secure sensitive data (encrypt passwords, PII)
   - Add audit logging for sensitive operations
   - Implement CSRF protection

### 10. **Documentation**
   - Expand API documentation with examples
   - Create developer onboarding guide
   - Document deployment procedures
   - Add architecture diagrams
   - Create user guides for each role

### 11. **DevOps & Deployment**
   - Containerize with Docker
   - Create docker-compose for local development
   - Set up CI/CD pipeline (GitHub Actions, GitLab CI)
   - Deploy to cloud platform (AWS, GCP, Azure)
   - Configure environment-based settings (dev, staging, prod)
   - Set up database backups and disaster recovery

### 12. **Advanced Features**
   - Implement full-text search (Elasticsearch)
   - Add real-time notifications (WebSockets)
   - Create admin dashboard
   - Add analytics and reporting
   - Implement recommendation engine
   - Add GraphQL API option

---

**Ready to build the future of Pokemon card trading!** 🎴✨
