# Backend Specification

## 1. System Summary

**System Name:** Pokemon Card Resell Platform

**Description:** 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.

**Core Purpose:** Provide a trusted platform for Pokemon card enthusiasts to conduct transactions with features including card catalog management, grading service integration, offer negotiation, order fulfillment, dispute resolution, and seller reputation tracking.

**Key Features:**
- User authentication and role-based access (guest, buyer, seller, moderator, admin)
- Comprehensive Pokemon card catalog with sets, categories, and detailed card information
- Seller listing management with condition grading and professional grading service integration
- Shopping cart and wishlist functionality
- Offer negotiation system for price flexibility
- Complete order management with payment processing and shipment tracking
- Buyer-seller messaging system
- Review and rating system for sellers
- Dispute resolution workflow
- Promotional campaigns and discount codes
- Platform fee calculation and seller payout tracking
- Reporting system for policy violations
- Notification system for user engagement

## 2. Source Input Summary

**Source Materials:**
- **DDL Schema:** 35 tables defining the complete database structure for users, cards, listings, orders, payments, communications, and platform management
- **PRD Document:** Comprehensive product requirements including user roles, entities, workflows, features, business rules, and non-functional requirements

**Schema Highlights:**
- User management with profiles, seller profiles, and addresses
- Card catalog with sets, cards, categories, and grading services
- Listing management with images and graded card information
- Shopping functionality with carts and wishlists
- Order processing with items, payments, and shipments
- Communication via conversations and messages
- Reviews, offers, disputes, and reports
- Transactions, notifications, promotions, and platform settings

**PRD Highlights:**
- Five user roles with distinct permissions
- 15 functional modules covering all platform operations
- Detailed workflows for registration, listing, purchasing, and dispute resolution
- Business rules for commissions, timeframes, and seller requirements
- Validation rules for data integrity
- Non-functional requirements for performance and security

## 3. Generation Mode

**Mode:** Strict

**Interpretation:** All endpoints, entities, fields, relationships, and business logic are derived directly from the provided DDL schema and PRD document. No additional features or modifications have been introduced beyond what is explicitly defined in the source materials.

## 4. Backend Scope

**Technology Stack:**
- **Framework:** FastAPI (Python 3.11+)
- **ORM:** SQLAlchemy 2.0+ with declarative models
- **Database:** SQLite (development), PostgreSQL-ready schema
- **Validation:** Pydantic v2 for request/response models
- **Package Management:** uv for dependency management
- **API Documentation:** Automatic OpenAPI/Swagger documentation via FastAPI

**Architecture Pattern:**
- Service layer pattern separating business logic from API routes
- Repository pattern for data access abstraction
- Dependency injection using FastAPI's `Depends(get_db)`
- Modular structure organized by functional domains

**Modules:**
1. **user_management** - Authentication, profiles, seller accounts, addresses
2. **card_catalog** - Card sets, cards, categories, categorization
3. **grading** - Grading services and graded card information
4. **listing_management** - Seller listings and images
5. **shopping** - Carts, cart items, wishlists, wishlist items
6. **order_management** - Orders, order items, payments, shipments
7. **offers** - Buyer offers and seller responses
8. **communication** - Conversations and messages
9. **reviews** - Buyer reviews and seller ratings
10. **disputes** - Dispute resolution workflow
11. **transactions** - Financial transaction tracking
12. **notifications** - User notification system
13. **reports** - Policy violation reporting
14. **promotions** - Promotional campaigns and usage tracking
15. **platform_settings** - Configurable platform parameters

## 5. Roles

| Role | Description | Key Permissions |
|------|-------------|-----------------|
| **guest** | Unauthenticated visitor | Browse cards, view listings, search catalog |
| **buyer** | Registered user who purchases cards | All guest permissions + add to cart, make purchases, leave reviews, create offers, manage wishlist |
| **seller** | User approved to sell cards | All buyer permissions + create listings, manage inventory, respond to offers, ship orders, respond to reviews |
| **moderator** | Platform content moderator | Review reports, moderate listings, resolve disputes (escalated), manage user content |
| **admin** | Platform administrator | Full system access, manage users, configure platform settings, view all transactions, manage promotions |

## 6. Entities and Fields

### User Management Module

#### User
**Table:** `users`  
**Description:** Registered user with authentication credentials and role assignments

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| email | str | Yes | User email address, must be unique |
| password_hash | str | Yes | Hashed password |
| role | str | Yes | User role: guest, buyer, seller, moderator, admin |
| is_active | bool | Yes | Whether account is active |
| is_verified | bool | Yes | Whether email is verified |
| last_login_at | Optional[datetime] | No | Last login timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** is_active

#### Userprofile
**Table:** `user_profiles`  
**Description:** Extended profile information for users

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| first_name | Optional[str] | No | User first name |
| last_name | Optional[str] | No | User last name |
| display_name | Optional[str] | No | Public display name |
| bio | Optional[str] | No | User biography |
| avatar_url | Optional[str] | No | Profile avatar URL |
| phone | Optional[str] | No | Phone number |
| location | Optional[str] | No | User location |
| timezone | Optional[str] | No | User timezone |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Sellerprofile
**Table:** `seller_profiles`  
**Description:** Additional information for users who sell cards

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| store_name | str | Yes | Seller store name |
| store_description | Optional[str] | No | Store description |
| store_logo_url | Optional[str] | No | Store logo URL |
| average_rating | Optional[float] | No | Average seller rating |
| total_sales | int | Yes | Total number of sales |
| total_reviews | int | Yes | Total number of reviews |
| response_time_hours | Optional[int] | No | Average response time in hours |
| is_verified_seller | bool | Yes | Whether seller is verified |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** is_verified_seller

#### Address
**Table:** `addresses`  
**Description:** Shipping or billing address associated with a user

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| address_type | str | Yes | Address type: shipping or billing |
| is_default | bool | Yes | Whether this is default address |
| recipient_name | str | Yes | Recipient name |
| address_line1 | str | Yes | Address line 1 |
| address_line2 | Optional[str] | No | Address line 2 |
| city | str | Yes | City |
| state | str | Yes | State or province |
| postal_code | str | Yes | Postal code |
| country | str | Yes | Country |
| phone | Optional[str] | No | Contact phone |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Card Catalog Module

#### Cardset
**Table:** `card_sets`  
**Description:** Pokemon TCG set or expansion

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| name | str | Yes | Set name |
| series | Optional[str] | No | Series name |
| release_date | Optional[date] | No | Release date |
| total_cards | Optional[int] | No | Total cards in set |
| set_code | Optional[str] | No | Unique set code |
| symbol_url | Optional[str] | No | Set symbol image URL |
| logo_url | Optional[str] | No | Set logo image URL |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Card
**Table:** `cards`  
**Description:** Master catalog entry for a Pokemon card

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| card_set_id | str | Yes | Reference to card set |
| name | str | Yes | Card name |
| pokemon_name | Optional[str] | No | Pokemon name |
| card_number | str | Yes | Card number in set |
| rarity | Optional[str] | No | Card rarity |
| card_type | Optional[str] | No | Card type: pokemon, trainer, energy |
| pokemon_type | Optional[str] | No | Pokemon type (Fire, Water, etc.) |
| hp | Optional[int] | No | Hit points |
| artist | Optional[str] | No | Card artist |
| image_url | Optional[str] | No | Card image URL |
| image_url_hires | Optional[str] | No | High resolution image URL |
| description | Optional[str] | No | Card description |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Category
**Table:** `categories`  
**Description:** Organizational grouping for cards

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| name | str | Yes | Category name |
| slug | str | Yes | URL-friendly slug |
| description | Optional[str] | No | Category description |
| parent_category_id | Optional[str] | No | Parent category reference |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Cardcategory
**Table:** `card_categories`  
**Description:** Many-to-many relationship between cards and categories

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| card_id | str | Yes | Reference to card |
| category_id | str | Yes | Reference to category |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Grading Module

#### Gradingservice
**Table:** `grading_services`  
**Description:** Third-party grading companies that authenticate and grade cards

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| name | str | Yes | Grading service name |
| abbreviation | str | Yes | Service abbreviation |
| website_url | Optional[str] | No | Service website URL |
| description | Optional[str] | No | Service description |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Gradedcard
**Table:** `graded_cards`  
**Description:** Information about professionally graded cards

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| listing_id | str | Yes | Reference to listing |
| grading_service_id | str | Yes | Reference to grading service |
| grade | str | Yes | Grade assigned |
| certification_number | Optional[str] | No | Certification number |
| grading_date | Optional[date] | No | Date card was graded |
| population_count | Optional[int] | No | Population count for this grade |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Listing Management Module

#### Listing
**Table:** `listings`  
**Description:** A specific card offered for sale by a seller

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| seller_id | str | Yes | Reference to seller user |
| card_id | str | Yes | Reference to card |
| title | str | Yes | Listing title |
| description | Optional[str] | No | Listing description |
| price | float | Yes | Listing price |
| quantity | int | Yes | Quantity available |
| condition | str | Yes | Card condition |
| language | str | Yes | Card language |
| is_first_edition | bool | Yes | Whether card is first edition |
| is_shadowless | bool | Yes | Whether card is shadowless |
| is_reverse_holo | bool | Yes | Whether card is reverse holo |
| accepts_offers | bool | Yes | Whether seller accepts offers |
| status | str | Yes | Listing status |
| views_count | int | Yes | Number of views |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

#### Listingimage
**Table:** `listing_images`  
**Description:** Photos of the actual card being sold

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| listing_id | str | Yes | Reference to listing |
| image_url | str | Yes | Image URL |
| display_order | int | Yes | Display order |
| is_primary | bool | Yes | Whether this is primary image |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Shopping Module

#### Cart
**Table:** `carts`  
**Description:** Shopping cart containing items a buyer intends to purchase

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Cartitem
**Table:** `cart_items`  
**Description:** Individual listing added to a cart

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| cart_id | str | Yes | Reference to cart |
| listing_id | str | Yes | Reference to listing |
| quantity | int | Yes | Quantity in cart |
| price_snapshot | float | Yes | Price at time of adding to cart |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Wishlist
**Table:** `wishlists`  
**Description:** Collection of cards a buyer is interested in purchasing

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| name | str | Yes | Wishlist name |
| is_public | bool | Yes | Whether wishlist is public |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Wishlistitem
**Table:** `wishlist_items`  
**Description:** Individual card saved to a wishlist

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| wishlist_id | str | Yes | Reference to wishlist |
| card_id | str | Yes | Reference to card |
| price_alert_threshold | Optional[float] | No | Price alert threshold |
| notes | Optional[str] | No | User notes |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Order Management Module

#### Order
**Table:** `orders`  
**Description:** A completed purchase transaction

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| order_number | str | Yes | Unique order number |
| buyer_id | str | Yes | Reference to buyer user |
| seller_id | str | Yes | Reference to seller user |
| status | str | Yes | Order status |
| subtotal | float | Yes | Order subtotal |
| shipping_cost | float | Yes | Shipping cost |
| tax_amount | float | Yes | Tax amount |
| platform_fee | float | Yes | Platform fee |
| total_amount | float | Yes | Total order amount |
| shipping_address_id | str | Yes | Reference to shipping address |
| billing_address_id | str | Yes | Reference to billing address |
| notes | Optional[str] | No | Order notes |
| cancelled_at | Optional[datetime] | No | Cancellation timestamp |
| cancellation_reason | Optional[str] | No | Cancellation reason |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

#### Orderitem
**Table:** `order_items`  
**Description:** Individual card purchase within an order

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| order_id | str | Yes | Reference to order |
| listing_id | str | Yes | Reference to listing |
| card_id | str | Yes | Reference to card |
| quantity | int | Yes | Quantity purchased |
| price | float | Yes | Price at time of purchase |
| condition | str | Yes | Card condition at time of purchase |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Payment
**Table:** `payments`  
**Description:** Payment transaction record

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| order_id | str | Yes | Reference to order |
| payment_method | str | Yes | Payment method used |
| amount | float | Yes | Payment amount |
| currency | str | Yes | Currency code |
| status | str | Yes | Payment status |
| transaction_id | Optional[str] | No | External transaction ID |
| payment_gateway | Optional[str] | No | Payment gateway used |
| payment_details | Optional[str] | No | Additional payment details as JSON |
| processed_at | Optional[datetime] | No | Processing timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

#### Shipment
**Table:** `shipments`  
**Description:** Shipping information for an order

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| order_id | str | Yes | Reference to order |
| carrier | str | Yes | Shipping carrier |
| tracking_number | Optional[str] | No | Tracking number |
| shipping_method | Optional[str] | No | Shipping method |
| status | str | Yes | Shipment status |
| shipped_at | Optional[datetime] | No | Shipment timestamp |
| estimated_delivery_date | Optional[date] | No | Estimated delivery date |
| delivered_at | Optional[datetime] | No | Delivery timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

### Offers Module

#### Offer
**Table:** `offers`  
**Description:** A buyer's proposed price for a listing

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| listing_id | str | Yes | Reference to listing |
| buyer_id | str | Yes | Reference to buyer user |
| offer_amount | float | Yes | Offered amount |
| message | Optional[str] | No | Buyer message with offer |
| status | str | Yes | Offer status |
| expires_at | datetime | Yes | Offer expiration timestamp |
| responded_at | Optional[datetime] | No | Seller response timestamp |
| response_message | Optional[str] | No | Seller response message |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

### Communication Module

#### Conversation
**Table:** `conversations`  
**Description:** Thread of messages between two users

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| participant1_id | str | Yes | Reference to first participant |
| participant2_id | str | Yes | Reference to second participant |
| listing_id | Optional[str] | No | Reference to listing context |
| order_id | Optional[str] | No | Reference to order context |
| last_message_at | Optional[datetime] | No | Last message timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

#### Message
**Table:** `messages`  
**Description:** Communication between buyer and seller

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| conversation_id | str | Yes | Reference to conversation |
| sender_id | str | Yes | Reference to sender user |
| message_text | str | Yes | Message content |
| is_read | bool | Yes | Whether message is read |
| read_at | Optional[datetime] | No | Read timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Reviews Module

#### Review
**Table:** `reviews`  
**Description:** Buyer feedback for a seller or transaction

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| order_id | str | Yes | Reference to order |
| reviewer_id | str | Yes | Reference to reviewer user |
| seller_id | str | Yes | Reference to seller user |
| rating | int | Yes | Rating from 1 to 5 |
| title | Optional[str] | No | Review title |
| comment | Optional[str] | No | Review comment |
| seller_response | Optional[str] | No | Seller response to review |
| seller_response_at | Optional[datetime] | No | Seller response timestamp |
| is_verified_purchase | bool | Yes | Whether purchase is verified |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Disputes Module

#### Dispute
**Table:** `disputes`  
**Description:** Formal complaint or issue raised about a transaction

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| order_id | str | Yes | Reference to order |
| complainant_id | str | Yes | Reference to complainant user |
| respondent_id | str | Yes | Reference to respondent user |
| reason | str | Yes | Dispute reason |
| description | str | Yes | Dispute description |
| status | str | Yes | Dispute status |
| resolution | Optional[str] | No | Resolution details |
| resolved_by_id | Optional[str] | No | Reference to resolver user |
| resolved_at | Optional[datetime] | No | Resolution timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

### Transactions Module

#### Transaction
**Table:** `transactions`  
**Description:** Financial transaction record for platform fees, seller payouts, and refunds

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| order_id | Optional[str] | No | Reference to order |
| transaction_type | str | Yes | Transaction type |
| amount | float | Yes | Transaction amount |
| currency | str | Yes | Currency code |
| status | str | Yes | Transaction status |
| description | Optional[str] | No | Transaction description |
| reference_id | Optional[str] | No | External reference ID |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

### Notifications Module

#### Notification
**Table:** `notifications`  
**Description:** System notifications for users

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| user_id | str | Yes | Reference to user |
| notification_type | str | Yes | Notification type |
| title | str | Yes | Notification title |
| message | str | Yes | Notification message |
| is_read | bool | Yes | Whether notification is read |
| read_at | Optional[datetime] | No | Read timestamp |
| action_url | Optional[str] | No | Action URL |
| related_entity_type | Optional[str] | No | Related entity type |
| related_entity_id | Optional[str] | No | Related entity ID |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Reports Module

#### Report
**Table:** `reports`  
**Description:** User-submitted reports of policy violations

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| reporter_id | str | Yes | Reference to reporter user |
| reported_user_id | Optional[str] | No | Reference to reported user |
| reported_listing_id | Optional[str] | No | Reference to reported listing |
| report_type | str | Yes | Report type |
| description | str | Yes | Report description |
| status | str | Yes | Report status |
| reviewed_by_id | Optional[str] | No | Reference to reviewer user |
| resolution_notes | Optional[str] | No | Resolution notes |
| resolved_at | Optional[datetime] | No | Resolution timestamp |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** status

### Promotions Module

#### Promotion
**Table:** `promotions`  
**Description:** Marketing campaigns, discount codes, and featured listings

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| code | Optional[str] | No | Promo code |
| name | str | Yes | Promotion name |
| description | Optional[str] | No | Promotion description |
| promotion_type | str | Yes | Promotion type |
| discount_percentage | Optional[float] | No | Discount percentage |
| discount_amount | Optional[float] | No | Discount amount |
| minimum_purchase_amount | Optional[float] | No | Minimum purchase amount |
| max_uses | Optional[int] | No | Maximum uses |
| current_uses | int | Yes | Current uses |
| starts_at | datetime | Yes | Start timestamp |
| expires_at | datetime | Yes | Expiration timestamp |
| is_active | bool | Yes | Whether promotion is active |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** is_active

#### Promotionusage
**Table:** `promotion_usages`  
**Description:** Tracking of promotion code usage by users

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| promotion_id | str | Yes | Reference to promotion |
| user_id | str | Yes | Reference to user |
| order_id | str | Yes | Reference to order |
| discount_applied | float | Yes | Discount amount applied |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

### Platform Settings Module

#### Platformsetting
**Table:** `platform_settings`  
**Description:** Configurable platform parameters and settings

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | str | Yes | Unique identifier |
| setting_key | str | Yes | Setting key |
| setting_value | str | Yes | Setting value |
| setting_type | str | Yes | Setting type: string, number, boolean, json |
| description | Optional[str] | No | Setting description |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

## 7. Enumerations

### UserRole
- **GUEST** - Guest
- **BUYER** - Buyer
- **SELLER** - Seller
- **MODERATOR** - Moderator
- **ADMIN** - Admin

### AddressType
- **SHIPPING** - Shipping
- **BILLING** - Billing

### CardType
- **POKEMON** - Pokemon
- **TRAINER** - Trainer
- **ENERGY** - Energy

### CardCondition
- **MINT** - Mint
- **NEAR_MINT** - Near Mint
- **LIGHTLY_PLAYED** - Lightly Played
- **MODERATELY_PLAYED** - Moderately Played
- **HEAVILY_PLAYED** - Heavily Played
- **DAMAGED** - Damaged

### ListingStatus
- **DRAFT** - Draft
- **ACTIVE** - Active
- **SOLD** - Sold
- **RESERVED** - Reserved
- **INACTIVE** - Inactive
- **REMOVED** - Removed

### OrderStatus
- **PENDING** - Pending
- **PAID** - Paid
- **PROCESSING** - Processing
- **SHIPPED** - Shipped
- **DELIVERED** - Delivered
- **CANCELLED** - Cancelled
- **REFUNDED** - Refunded
- **DISPUTED** - Disputed

### PaymentMethod
- **CREDIT_CARD** - Credit Card
- **DEBIT_CARD** - Debit Card
- **PAYPAL** - PayPal
- **STRIPE** - Stripe
- **BANK_TRANSFER** - Bank Transfer

### PaymentStatus
- **PENDING** - Pending
- **PROCESSING** - Processing
- **COMPLETED** - Completed
- **FAILED** - Failed
- **REFUNDED** - Refunded
- **CANCELLED** - Cancelled

### ShipmentStatus
- **PENDING** - Pending
- **LABEL_CREATED** - Label Created
- **IN_TRANSIT** - In Transit
- **OUT_FOR_DELIVERY** - Out For Delivery
- **DELIVERED** - Delivered
- **FAILED** - Failed
- **RETURNED** - Returned

### OfferStatus
- **PENDING** - Pending
- **ACCEPTED** - Accepted
- **REJECTED** - Rejected
- **CANCELLED** - Cancelled
- **EXPIRED** - Expired

### DisputeReason
- **ITEM_NOT_RECEIVED** - Item Not Received
- **ITEM_NOT_AS_DESCRIBED** - Item Not As Described
- **DAMAGED_ITEM** - Damaged Item
- **COUNTERFEIT** - Counterfeit
- **OTHER** - Other

### DisputeStatus
- **OPEN** - Open
- **UNDER_REVIEW** - Under Review
- **RESOLVED** - Resolved
- **CLOSED** - Closed
- **ESCALATED** - Escalated

### TransactionType
- **SALE** - Sale
- **PURCHASE** - Purchase
- **REFUND** - Refund
- **PAYOUT** - Payout
- **PLATFORM_FEE** - Platform Fee
- **ADJUSTMENT** - Adjustment

### TransactionStatus
- **PENDING** - Pending
- **COMPLETED** - Completed
- **FAILED** - Failed
- **CANCELLED** - Cancelled

### NotificationType
- **ORDER** - Order
- **MESSAGE** - Message
- **OFFER** - Offer
- **REVIEW** - Review
- **SHIPMENT** - Shipment
- **PAYMENT** - Payment
- **SYSTEM** - System
- **PROMOTION** - Promotion

### ReportType
- **FRAUDULENT_LISTING** - Fraudulent Listing
- **COUNTERFEIT** - Counterfeit
- **INAPPROPRIATE_CONTENT** - Inappropriate Content
- **HARASSMENT** - Harassment
- **SPAM** - Spam
- **OTHER** - Other

### ReportStatus
- **PENDING** - Pending
- **UNDER_REVIEW** - Under Review
- **RESOLVED** - Resolved
- **DISMISSED** - Dismissed

### PromotionType
- **PERCENTAGE_DISCOUNT** - Percentage Discount
- **FIXED_DISCOUNT** - Fixed Discount
- **FREE_SHIPPING** - Free Shipping
- **FEATURED_LISTING** - Featured Listing

### SettingType
- **STRING** - String
- **NUMBER** - Number
- **BOOLEAN** - Boolean
- **JSON** - JSON

## 8. Relationships

### User Relationships
- User has one UserProfile (required navigation)
- User has zero or one SellerProfile (required navigation)
- User has many Addresses (required navigation)
- User has many Listings as seller (required navigation)
- User has many Orders as buyer (required navigation)
- User has many Orders as seller (required navigation)
- User has one Cart (required navigation)
- User has many Reviews as reviewer (no navigation)
- User has many Reviews as seller (required navigation)
- User has many Offers as buyer (required navigation)
- User has one Wishlist (required navigation)
- User has many Messages as sender (no navigation)
- User has many Conversations as participant (required navigation)
- User has many Disputes as complainant (required navigation)
- User has many Disputes as respondent (required navigation)
- User has many Transactions (required navigation)
- User has many Notifications (no navigation)
- User has many Reports as reporter (no navigation)

### Card Catalog Relationships
- CardSet has many Cards (required navigation)
- Card belongs to one CardSet (required navigation)
- Card has many Listings (no navigation)
- Card has many WishlistItems (no navigation)
- Card has many CardCategories (required navigation)
- Category has many CardCategories (no navigation)
- Category has one parent Category (required navigation)
- CardCategory belongs to one Card (required navigation)
- CardCategory belongs to one Category (required navigation)

### Listing Relationships
- Listing belongs to one Card (required navigation)
- Listing belongs to one User as seller (required navigation)
- Listing has zero or one GradedCard (required navigation)
- Listing has many ListingImages (required navigation)
- Listing has many CartItems (no navigation)
- Listing has many OrderItems (no navigation)
- Listing has many Offers (required navigation)

### Grading Relationships
- GradedCard belongs to one Listing (no navigation)
- GradedCard belongs to one GradingService (required navigation)
- GradingService has many GradedCards (no navigation)

### Shopping Relationships
- Cart belongs to one User (no navigation)
- Cart has many CartItems (required navigation)
- CartItem belongs to one Cart (no navigation)
- CartItem belongs to one Listing (required navigation)
- Wishlist belongs to one User (no navigation)
- Wishlist has many WishlistItems (required navigation)
- WishlistItem belongs to one Wishlist (no navigation)
- WishlistItem belongs to one Card (required navigation)

### Order Relationships
- Order belongs to one User as buyer (required navigation)
- Order belongs to one User as seller (required navigation)
- Order has many OrderItems (required navigation)
- Order has one Payment (required navigation)
- Order has zero or one Shipment (required navigation)
- Order belongs to one Address as shipping address (required navigation)
- Order belongs to one Address as billing address (required navigation)
- Order has zero or one Review (no navigation)
- Order has zero or one Dispute (no navigation)
- OrderItem belongs to one Order (no navigation)
- OrderItem belongs to one Listing (required navigation)
- OrderItem belongs to one Card (required navigation)
- Payment belongs to one Order (no navigation)
- Shipment belongs to one Order (no navigation)

### Communication Relationships
- Conversation has two Users as participants (required navigation)
- Conversation has many Messages (required navigation)
- Conversation belongs to zero or one Listing (required navigation)
- Conversation belongs to zero or one Order (required navigation)
- Message belongs to one Conversation (no navigation)
- Message belongs to one User as sender (required navigation)

### Review and Offer Relationships
- Review belongs to one Order (required navigation)
- Review belongs to one User as reviewer (required navigation)
- Review belongs to one User as seller (required navigation)
- Offer belongs to one Listing (required navigation)
- Offer belongs to one User as buyer (required navigation)

### Dispute Relationships
- Dispute belongs to one Order (required navigation)
- Dispute belongs to one User as complainant (required navigation)
- Dispute belongs to one User as respondent (required navigation)
- Dispute belongs to zero or one User as resolver (required navigation)

### Transaction and Notification Relationships
- Transaction belongs to one User (required navigation)
- Transaction belongs to zero or one Order (required navigation)
- Notification belongs to one User (no navigation)

### Report Relationships
- Report belongs to one User as reporter (required navigation)
- Report belongs to zero or one User as reported user (required navigation)
- Report belongs to zero or one Listing as reported listing (required navigation)
- Report belongs to zero or one User as reviewer (required navigation)

### Promotion Relationships
- Promotion has many PromotionUsages (no navigation)
- PromotionUsage belongs to one Promotion (required navigation)
- PromotionUsage belongs to one User (required navigation)
- PromotionUsage belongs to one Order (required navigation)

## 9. API Endpoints

### User Management Endpoints

#### User CRUD
- `POST /users` - Create user
- `GET /users/{id}` - Get user by ID
- `GET /users` - List users (with pagination and filters)
- `PUT /users/{id}` - Update user
- `DELETE /users/{id}` - Delete user

#### UserProfile CRUD
- `POST /user-profiles` - Create user profile
- `GET /user-profiles/{id}` - Get user profile by ID
- `GET /user-profiles` - List user profiles
- `PUT /user-profiles/{id}` - Update user profile
- `DELETE /user-profiles/{id}` - Delete user profile

#### SellerProfile CRUD
- `POST /seller-profiles` - Create seller profile
- `GET /seller-profiles/{id}` - Get seller profile by ID
- `GET /seller-profiles` - List seller profiles
- `PUT /seller-profiles/{id}` - Update seller profile
- `DELETE /seller-profiles/{id}` - Delete seller profile

#### Address CRUD
- `POST /addresses` - Create address
- `GET /addresses/{id}` - Get address by ID
- `GET /addresses` - List addresses
- `PUT /addresses/{id}` - Update address
- `DELETE /addresses/{id}` - Delete address

#### User Actions
- `POST /users/register` - Register new user
- `POST /users/login` - Authenticate user
- `POST /users/{id}/verify-email` - Verify email address
- `POST /users/{id}/become-seller` - Apply to become seller
- `GET /users/{id}/profile` - Get user profile details (with eager loading)
- `GET /users/{id}/seller-dashboard` - Get seller dashboard
- `GET /users/{id}/buyer-dashboard` - Get buyer dashboard

### Card Catalog Endpoints

#### CardSet CRUD
- `POST /card-sets` - Create card set
- `GET /card-sets/{id}` - Get card set by ID
- `GET /card-sets` - List card sets
- `PUT /card-sets/{id}` - Update card set
- `DELETE /card-sets/{id}` - Delete card set

#### Card CRUD
- `POST /cards` - Create card
- `GET /cards/{id}` - Get card by ID
- `GET /cards` - List cards
- `PUT /cards/{id}` - Update card
- `DELETE /cards/{id}` - Delete card

#### Category CRUD
- `POST /categories` - Create category
- `GET /categories/{id}` - Get category by ID
- `GET /categories` - List categories
- `PUT /categories/{id}` - Update category
- `DELETE /categories/{id}` - Delete category

#### Card Actions
- `GET /cards/search` - Search cards (with filters for set, type, rarity, etc.)

### Grading Endpoints

#### GradingService CRUD
- `POST /grading-services` - Create grading service
- `GET /grading-services/{id}` - Get grading service by ID
- `GET /grading-services` - List grading services
- `PUT /grading-services/{id}` - Update grading service
- `DELETE /grading-services/{id}` - Delete grading service

#### GradedCard CRUD
- `POST /graded-cards` - Create graded card
- `GET /graded-cards/{id}` - Get graded card by ID
- `GET /graded-cards` - List graded cards
- `PUT /graded-cards/{id}` - Update graded card
- `DELETE /graded-cards/{id}` - Delete graded card

### Listing Management Endpoints

#### Listing CRUD
- `POST /listings` - Create listing
- `GET /listings/{id}` - Get listing by ID
- `GET /listings` - List listings
- `PUT /listings/{id}` - Update listing
- `DELETE /listings/{id}` - Delete listing

#### ListingImage CRUD
- `POST /listing-images` - Create listing image
- `GET /listing-images/{id}` - Get listing image by ID
- `GET /listing-images` - List listing images
- `PUT /listing-images/{id}` - Update listing image
- `DELETE /listing-images/{id}` - Delete listing image

#### Listing Actions
- `GET /listings/{id}/details` - Get listing details (with eager loading)
- `POST /listings/{id}/publish` - Publish listing
- `POST /listings/{id}/deactivate` - Deactivate listing
- `GET /listings/search` - Search listings (with filters)

### Shopping Endpoints

#### Cart CRUD
- `POST /carts` - Create cart
- `GET /carts/{id}` - Get cart by ID
- `GET /carts` - List carts
- `PUT /carts/{id}` - Update cart
- `DELETE /carts/{id}` - Delete cart

#### CartItem CRUD
- `POST /cart-items` - Create cart item
- `GET /cart-items/{id}` - Get cart item by ID
- `GET /cart-items` - List cart items
- `PUT /cart-items/{id}` - Update cart item
- `DELETE /cart-items/{id}` - Delete cart item

#### Wishlist CRUD
- `POST /wishlists` - Create wishlist
- `GET /wishlists/{id}` - Get wishlist by ID
- `GET /wishlists` - List wishlists
- `PUT /wishlists/{id}` - Update wishlist
- `DELETE /wishlists/{id}` - Delete wishlist

#### WishlistItem CRUD
- `POST /wishlist-items` - Create wishlist item
- `GET /wishlist-items/{id}` - Get wishlist item by ID
- `GET /wishlist-items` - List wishlist items
- `PUT /wishlist-items/{id}` - Update wishlist item
- `DELETE /wishlist-items/{id}` - Delete wishlist item

#### Shopping Actions
- `GET /carts/{id}/details` - Get cart details (with eager loading)
- `POST /carts/{id}/checkout` - Checkout cart
- `GET /wishlists/{id}/details` - Get wishlist details (with eager loading)

### Order Management Endpoints

#### Order CRUD
- `POST /orders` - Create order
- `GET /orders/{id}` - Get order by ID
- `GET /orders` - List orders
- `PUT /orders/{id}` - Update order
- `DELETE /orders/{id}` - Delete order

#### OrderItem CRUD
- `POST /order-items` - Create order item
- `GET /order-items/{id}` - Get order item by ID
- `GET /order-items` - List order items
- `PUT /order-items/{id}` - Update order item
- `DELETE /order-items/{id}` - Delete order item

#### Payment CRUD
- `POST /payments` - Create payment
- `GET /payments/{id}` - Get payment by ID
- `GET /payments` - List payments
- `PUT /payments/{id}` - Update payment
- `DELETE /payments/{id}` - Delete payment

#### Shipment CRUD
- `POST /shipments` - Create shipment
- `GET /shipments/{id}` - Get shipment by ID
- `GET /shipments` - List shipments
- `PUT /shipments/{id}` - Update shipment
- `DELETE /shipments/{id}` - Delete shipment

#### Order Actions
- `GET /orders/{id}/details` - Get order details (with eager loading)
- `POST /orders/{id}/ship` - Mark order as shipped
- `POST /orders/{id}/cancel` - Cancel order
- `POST /orders/{id}/confirm-delivery` - Confirm order delivery
- `GET /orders/{id}/tracking` - Get order tracking info

### Offer Endpoints

#### Offer CRUD
- `POST /offers` - Create offer
- `GET /offers/{id}` - Get offer by ID
- `GET /offers` - List offers
- `PUT /offers/{id}` - Update offer
- `DELETE /offers/{id}` - Delete offer

#### Offer Actions
- `POST /offers/{id}/accept` - Accept offer
- `POST /offers/{id}/reject` - Reject offer
- `POST /offers/{id}/counter` - Counter offer

### Communication Endpoints

#### Conversation CRUD
- `POST /conversations` - Create conversation
- `GET /conversations/{id}` - Get conversation by ID
- `GET /conversations` - List conversations
- `PUT /conversations/{id}` - Update conversation
- `DELETE /conversations/{id}` - Delete conversation

#### Message CRUD
- `POST /messages` - Create message
- `GET /messages/{id}` - Get message by ID
- `GET /messages` - List messages
- `PUT /messages/{id}` - Update message
- `DELETE /messages/{id}` - Delete message

#### Communication Actions
- `GET /conversations/{id}/details` - Get conversation details (with eager loading)

### Review Endpoints

#### Review CRUD
- `POST /reviews` - Create review
- `GET /reviews/{id}` - Get review by ID
- `GET /reviews` - List reviews
- `PUT /reviews/{id}` - Update review
- `DELETE /reviews/{id}` - Delete review

#### Review Actions
- `GET /reviews/{id}/details` - Get review details (with eager loading)
- `POST /reviews/{id}/respond` - Seller responds to review

### Dispute Endpoints

#### Dispute CRUD
- `POST /disputes` - Create dispute
- `GET /disputes/{id}` - Get dispute by ID
- `GET /disputes` - List disputes
- `PUT /disputes/{id}` - Update dispute
- `DELETE /disputes/{id}` - Delete dispute

#### Dispute Actions
- `GET /disputes/{id}/details` - Get dispute details (with eager loading)
- `POST /disputes/{id}/resolve` - Resolve dispute

### Transaction Endpoints

#### Transaction CRUD
- `POST /transactions` - Create transaction
- `GET /transactions/{id}` - Get transaction by ID
- `GET /transactions` - List transactions
- `PUT /transactions/{id}` - Update transaction
- `DELETE /transactions/{id}` - Delete transaction

### Notification Endpoints

#### Notification CRUD
- `POST /notifications` - Create notification
- `GET /notifications/{id}` - Get notification by ID
- `GET /notifications` - List notifications
- `PUT /notifications/{id}` - Update notification
- `DELETE /notifications/{id}` - Delete notification

#### Notification Actions
- `POST /notifications/{id}/mark-read` - Mark notification as read

### Report Endpoints

#### Report CRUD
- `POST /reports` - Create report
- `GET /reports/{id}` - Get report by ID
- `GET /reports` - List reports
- `PUT /reports/{id}` - Update report
- `DELETE /reports/{id}` - Delete report

#### Report Actions
- `POST /reports/{id}/review` - Review report

### Promotion Endpoints

#### Promotion CRUD
- `POST /promotions` - Create promotion
- `GET /promotions/{id}` - Get promotion by ID
- `GET /promotions` - List promotions
- `PUT /promotions/{id}` - Update promotion
- `DELETE /promotions/{id}` - Delete promotion

#### PromotionUsage CRUD
- `POST /promotion-usages` - Create promotion usage
- `GET /promotion-usages/{id}` - Get promotion usage by ID
- `GET /promotion-usages` - List promotion usages
- `PUT /promotion-usages/{id}` - Update promotion usage
- `DELETE /promotion-usages/{id}` - Delete promotion usage

### Platform Settings Endpoints

#### PlatformSetting CRUD
- `POST /platform-settings` - Create platform setting
- `GET /platform-settings/{id}` - Get platform setting by ID
- `GET /platform-settings` - List platform settings
- `PUT /platform-settings/{id}` - Update platform setting
- `DELETE /platform-settings/{id}` - Delete platform setting

## 10. Workflow Logic

### User Registration and Verification
1. User submits registration with email and password
2. System creates User record with `is_verified=false` and `is_active=true`
3. System creates associated UserProfile record
4. System sends verification email with token
5. User clicks verification link
6. System updates `is_verified=true`
7. User can now make purchases

### Seller Account Application
1. Verified user submits seller application
2. System creates SellerProfile with `is_verified_seller=false`
3. Admin reviews application
4. Admin approves or rejects
5. If approved, system updates `is_verified_seller=true`
6. User role updated to include seller permissions
7. Seller can now create listings

### Listing Creation and Publication
1. Seller creates listing in draft status
2. Seller adds card details, price, condition, quantity
3. Seller uploads minimum 2 images (front and back)
4. If graded card, seller adds grading information
5. Seller publishes listing
6. System validates listing meets requirements
7. Listing status changes to "active"
8. Listing appears in search results

### Card Search and Filtering
1. User enters search criteria (name, set, type, rarity, condition, price range)
2. System queries cards and active listings
3. System applies filters and sorting
4. System returns paginated results with card and listing details
5. User can view listing details with eager-loaded relationships

### Add to Cart and Checkout
1. Buyer adds listing to cart
2. System creates CartItem with price snapshot
3. System validates listing availability and quantity
4. Buyer proceeds to checkout
5. System validates cart items still available
6. System calculates subtotal, shipping, tax, platform fee
7. Buyer applies promotion code (if applicable)
8. System validates promotion and applies discount
9. Buyer selects shipping and billing addresses
10. Buyer submits payment
11. Payment gateway processes payment
12. System creates Order, OrderItems, Payment records
13. System updates listing quantities
14. System clears cart
15. System creates notification for buyer and seller
16. System creates transaction records for platform fee

### Make Offer and Negotiation
1. Buyer submits offer on listing with `accepts_offers=true`
2. System validates offer amount (minimum 50% of asking price)
3. System creates Offer with status "pending" and 48-hour expiration
4. System notifies seller
5. Seller accepts, rejects, or counters offer
6. If accepted, system creates order at offer price
7. If rejected, offer status changes to "rejected"
8. If countered, buyer can accept or reject counter
9. If no response within 48 hours, offer expires

### Order Fulfillment with Tracking
1. Seller receives order notification
2. Seller has 3 business days to ship
3. Seller creates shipment with carrier and tracking number
4. System updates order status to "shipped"
5. System notifies buyer with tracking information
6. Carrier updates tracking status via webhook/API
7. System updates shipment status
8. When delivered, system updates order status to "delivered"
9. After 7 days, order auto-completes if no disputes
10. System processes seller payout after 7-day hold period

### Leave Review After Order Completion
1. Order status is "delivered" or "completed"
2. Buyer has 30 days to leave review
3. Buyer submits rating (1-5) and optional comment
4. System creates Review with `is_verified_purchase=true`
5. System updates seller's average rating and total reviews
6. System notifies seller of new review
7. Seller can respond to review within 14 days
8. System updates review with seller response

### Open and Resolve Dispute
1. Buyer opens dispute within 30 days of delivery
2. System creates Dispute with status "open"
3. System notifies seller and admin/moderator
4. Buyer and seller communicate through dispute system
5. Moderator reviews evidence and communications
6. Moderator makes resolution decision
7. System updates dispute status to "resolved"
8. If refund required, system processes refund transaction
9. System updates order status accordingly
10. System creates transaction records for refund

### Wishlist Management with Price Alerts
1. Buyer creates wishlist
2. Buyer adds cards to wishlist with optional price alert threshold
3. When new listing created for wishlist card, system checks price
4. If price at or below threshold, system creates notification
5. Buyer receives price alert notification
6. Buyer can view listing and add to cart

### Buyer-Seller Messaging
1. Buyer initiates conversation about listing or order
2. System creates Conversation with context (listing_id or order_id)
3. Buyer sends message
4. System creates Message record
5. System notifies recipient
6. Recipient reads message, system updates `is_read=true`
7. Recipient responds
8. Conversation continues until resolved

### Seller Payout Processing
1. Order completes successfully
2. System holds funds for 7 days
3. After hold period, system creates payout transaction
4. System calculates seller amount (total - platform fee)
5. System creates Transaction record with type "payout"
6. Payment gateway processes payout to seller account
7. System updates transaction status to "completed"
8. System notifies seller of payout

### Apply Promotion Code at Checkout
1. Buyer enters promotion code at checkout
2. System validates code exists and is active
3. System checks promotion start/end dates
4. System checks usage limits (max_uses vs current_uses)
5. System checks minimum purchase amount requirement
6. System calculates discount (percentage or fixed amount)
7. System applies discount to order total
8. System creates PromotionUsage record
9. System increments promotion current_uses
10. Order proceeds with discounted total

### Report Listing or User
1. User submits report with type and description
2. System creates Report with status "pending"
3. System notifies moderators
4. Moderator reviews report and evidence
5. Moderator takes action (remove listing, warn user, suspend account)
6. Moderator updates report status to "resolved" or "dismissed"
7. System notifies reporter of outcome
8. If listing removed, system updates listing status to "removed"

### Admin Moderation of Listings and Users
1. Admin views pending reports and flagged content
2. Admin reviews listing details and user history
3. Admin can deactivate listings, suspend users, or take no action
4. If user suspended, system bulk updates all user's listings to "inactive"
5. System creates notifications for affected users
6. System logs moderation actions for audit trail

## 11. Business Logic

### Commission and Fee Calculation
- Platform charges configurable commission on each sale (stored in PlatformSetting)
- Commission calculated as percentage of order subtotal
- Platform fee added to order total and paid by buyer
- Seller receives order subtotal minus platform fee
- Tax calculated based on buyer's shipping address
- Shipping cost added to order total

### Order Timing Rules
- Sellers must ship orders within 3 business days of payment
- Orders cannot be cancelled after shipment
- Buyers have 30 days after delivery to open disputes
- Orders auto-complete 7 days after delivery confirmation
- Seller payouts held for 7 days after order completion

### Offer Rules
- Offers must be at least 50% of asking price
- Offers expire after 48 hours if not responded to
- Only one active offer per buyer per listing
- Seller can accept, reject, or counter offer
- Accepted offers create orders at offer price

### Review Rules
- Only verified buyers can leave reviews (order must be completed)
- One review per order
- Reviews can be submitted within 30 days of order completion
- Sellers can respond to reviews within 14 days
- Reviews update seller's average rating and total review count

### Seller Suspension Rules
- Sellers with >25% dispute rate are automatically suspended
- Suspended sellers cannot create new listings
- Existing active listings are deactivated
- Suspended sellers can still fulfill existing orders

### Cart and Reservation Rules
- Cart items reserve inventory for 15 minutes
- After 15 minutes of inactivity, reservation expires
- Checkout validates all items still available
- Price snapshots stored in cart items for price change detection

### Listing Requirements
- Listings must have minimum 2 photos (front and back)
- Listing price must be greater than $0.01
- Quantity must be between 1 and 999
- Graded cards must include certification number
- Sellers must complete seller profile before creating listings

### Authentication and Verification
- Users must verify email before making purchases
- Email verification required within 7 days of registration
- Unverified users can browse but cannot purchase
- Password must meet complexity requirements

### Dispute Resolution
- Disputes must be opened within 30 days of delivery
- Moderators review disputes and make final decisions
- Refunds processed automatically based on dispute resolution
- Dispute rate tracked per seller for suspension threshold

### Promotion Validation
- Promotion codes must be active and within date range
- Usage limits enforced (max_uses vs current_uses)
- Minimum purchase amount requirements validated
- One promotion per order
- Promotion discounts applied before tax calculation

## 12. Validation Rules

### User Validation
- Email must be valid format and unique across all users
- Password must be minimum 8 characters with uppercase, lowercase, and number
- Display name must be unique if provided
- Phone number must be valid format if provided

### Listing Validation
- Listing quantity must be between 1 and 999
- Listing price must be greater than $0.01
- Condition must be one of valid CardCondition enum values
- Language must be valid ISO language code
- Minimum 2 listing images required for publication
- At least one image must be marked as primary

### Offer Validation
- Offer amount must be positive
- Offer amount must be at least 50% of listing price
- Offer amount cannot exceed listing price
- Buyer cannot make offer on own listing
- Listing must have `accepts_offers=true`

### Review Validation
- Rating must be between 1 and 5 (integer)
- Review can only be submitted for completed orders
- Reviewer must be the buyer of the order
- One review per order (no duplicates)

### Order Validation
- Payment amount must match order total
- Shipping address must include all required fields
- Billing address must include all required fields
- Order items must reference available listings
- Order quantities cannot exceed listing quantities

### Address Validation
- Recipient name required and non-empty
- Address line 1 required and non-empty
- City, state, postal code, country all required
- Postal code must match country format
- Phone number must be valid format if provided

### Payment Validation
- Payment amount must be positive
- Currency must be valid ISO currency code
- Payment method must be one of valid PaymentMethod enum values
- Transaction ID required for completed payments

### Shipment Validation
- Tracking number format must be valid for carrier
- Carrier must be one of supported carriers
- Estimated delivery date must be in future
- Shipment can only be created for paid orders

### Dispute Validation
- Dispute must be opened within 30 days of delivery
- Dispute reason must be one of valid DisputeReason enum values
- Description required and minimum 20 characters
- Dispute can only be opened once per order

### Promotion Validation
- Promo code must be unique if provided
- Discount percentage must be between 0 and 100
- Discount amount must be positive if provided
- Start date must be before end date
- Max uses must be positive if provided
- Minimum purchase amount must be positive if provided

### Report Validation
- Report type must be one of valid ReportType enum values
- Description required and minimum 20 characters
- Must report either user or listing (not both)
- Cannot report own content

### Platform Setting Validation
- Setting key must be unique
- Setting type must be one of valid SettingType enum values
- Setting value must match setting type format
- Critical settings cannot be deleted

## 13. Implementation Notes

### Technology Stack
- **Framework:** FastAPI for high-performance async API endpoints
- **ORM:** SQLAlchemy 2.0+ with declarative models for database abstraction
- **Database:** SQLite for development, schema designed for PostgreSQL compatibility
- **Validation:** Pydantic v2 for request/response models with automatic validation
- **Package Management:** uv for fast, reliable dependency management
- **Documentation:** Automatic OpenAPI/Swagger documentation via FastAPI

### Architecture Patterns
- **Service Layer Pattern:** Business logic separated from API routes in service classes
- **Repository Pattern:** Data access abstraction for testability and maintainability
- **Dependency Injection:** FastAPI's `Depends(get_db)` for database session management
- **Modular Structure:** Code organized by functional domains (15 modules)

### Database Design
- All tables use string UUIDs as primary keys for distributed system compatibility
- Timestamps (created_at, updated_at) on all entities for audit trail
- Soft deletes not used; records marked inactive or permanently deleted
- Foreign key constraints enforced at database level
- Indexes on frequently queried fields (email, order_number, tracking_number)

### API Design
- RESTful endpoints following standard conventions
- Pagination on all list endpoints (default 50 items per page)
- Filtering and sorting support on list endpoints
- Eager loading for detail endpoints to minimize N+1 queries
- Consistent error response format with status codes
- Request/response models validated with Pydantic

### Security Considerations
- Password hashing using bcrypt or Argon2
- Email verification tokens with expiration
- Rate limiting on authentication endpoints
- Input sanitization to prevent SQL injection
- CORS configuration for frontend integration
- Sensitive data (password_hash) excluded from API responses

### Performance Optimization
- Database connection pooling
- Eager loading for related entities on detail endpoints
- Batch operations for bulk updates (seller suspension, cart checkout)
- Caching for frequently accessed data (card catalog, platform settings)
- Async endpoints for I/O-bound operations

### Error Handling
- Custom exception classes for business logic errors
- HTTP status codes following REST conventions
- Detailed error messages for validation failures
- Logging of all errors for debugging
- Graceful degradation for external service failures

### Testing Strategy
- Unit tests for service layer business logic
- Integration tests for API endpoints
- Database fixtures for test data
- Mock external services (payment gateway, email)
- Test coverage target of 80%+

### Deployment Considerations
- Environment-based configuration (dev, staging, production)
- Database migrations managed separately (future: Alembic)
- Health check endpoint for monitoring
- Logging configuration for production
- Docker containerization (future improvement)

## 14. Assumptions

### Platform Operations
- Platform operates in USD as primary currency
- All timestamps stored in UTC
- Platform supports single-seller orders (no multi-seller checkout)
- Tax calculation based on buyer's shipping address
- Business days exclude weekends and holidays

### External Integrations
- Payment processing handled by third-party gateway (Stripe/PayPal)
- Image storage handled by cloud storage service (AWS S3)
- Email delivery handled by third-party service (SendGrid/Mailgun)
- Shipping tracking integrated with carrier APIs
- SMS notifications not implemented in initial version

### Data Management
- Card catalog pre-populated from external data source (Pokemon TCG API)
- Grading services manually added by administrators
- Platform settings configured by administrators
- User-generated content (listings, reviews) moderated by moderators
- Soft deletes not used; records permanently deleted or marked inactive

### User Behavior
- Users provide accurate information during registration
- Sellers ship items as described in listings
- Buyers inspect items upon delivery
- Disputes opened in good faith
- Users read and accept terms of service

### Business Rules
- Platform commission rate configurable but typically 5-10%
- Seller payout hold period fixed at 7 days
- Order auto-completion period fixed at 7 days after delivery
- Dispute window fixed at 30 days after delivery
- Offer expiration fixed at 48 hours

### Technical Constraints
- Maximum file size for images: 5MB
- Maximum listing images per listing: 10
- Maximum cart items per user: 100
- Maximum wishlist items per wishlist: 500
- API rate limit: 100 requests per minute per user

## 15. Future Improvements

### Authentication and Authorization
- JWT token-based authentication
- Role-based access control (RBAC) with granular permissions
- OAuth2 integration for social login (Google, Facebook)
- Two-factor authentication (2FA) for enhanced security
- API key management for third-party integrations

### Database and Migrations
- Alembic for database schema migrations
- PostgreSQL as production database
- Read replicas for scaling read operations
- Database backup and recovery procedures
- Data archival strategy for old records

### Testing and Quality
- Comprehensive unit test suite with 90%+ coverage
- Integration tests for all API endpoints
- End-to-end tests for critical workflows
- Performance testing and load testing
- Security testing and penetration testing

### Deployment and Operations
- Docker containerization for consistent deployments
- Kubernetes orchestration for scaling
- CI/CD pipeline for automated testing and deployment
- Monitoring and alerting (Prometheus, Grafana)
- Centralized logging (ELK stack)

### Advanced Features
- Auction-style listings with bidding
- Multi-seller checkout support
- Advanced analytics and reporting for sellers
- Mobile app for iOS and Android
- Real-time chat between buyers and sellers
- Integration with Pokemon TCG Online for digital card trading
- AI-powered card condition assessment from photos
- Bulk listing import for sellers
- Collection management and portfolio tracking
- Social features (follow sellers, share collections)

### Security Enhancements
- Advanced fraud detection and prevention
- IP-based rate limiting and blocking
- Content security policy (CSP) headers
- Regular security audits and vulnerability scanning
- GDPR compliance features (data export, right to be forgotten)

### Internationalization
- Multi-language support
- Multi-currency support with real-time exchange rates
- Localized content and translations
- Regional shipping options and carriers
- Country-specific tax calculations

### Business Features
- Subscription plans for sellers with premium features
- Integration with grading service APIs for automatic verification
- Marketplace for card grading services
- Consignment selling options
- Trade-in program for cards
- Gift cards and store credit
- Loyalty program and rewards

### Performance and Scalability
- Redis caching for frequently accessed data
- CDN for static assets and images
- Database query optimization and indexing
- Horizontal scaling with load balancers
- Asynchronous task processing (Celery)
- WebSocket support for real-time updates
