# ThrillWiki: System Architecture Overview

## 🎯 Executive Summary

**ThrillWiki** is a comprehensive theme park and ride tracking platform built with React, TypeScript, Vite, Tailwind CSS, Supabase (PostgreSQL), and CloudFlare Images. The application implements a **moderation-first architecture** where all user-generated content flows through a sophisticated approval queue before going live.

### Core Technology Stack
- **Frontend**: React 18.3, TypeScript, Vite, Tailwind CSS, shadcn/ui
- **Backend**: Supabase (PostgreSQL 15), Edge Functions (Deno)
- **Storage**: CloudFlare Images (direct upload API)
- **Notifications**: Novu Cloud (multi-channel)
- **State Management**: React Query (TanStack Query), React Hook Form, State Machines
- **Authentication**: Supabase Auth with MFA (TOTP), OAuth (Google, Discord)

---

## 📐 High-Level Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                         USERS (Web Browser)                      │
└───────────────────────────┬─────────────────────────────────────┘
                            │
                            ▼
┌───────────────────────────────────────────────────────────────┐
│                    REACT FRONTEND (SPA)                        │
│  - React Router (client-side routing)                          │
│  - React Query (data caching/sync)                             │
│  - shadcn/ui + Tailwind CSS                                    │
│  - State Machines (moderation, auth flows)                     │
└───────────────────────┬───────────────────────────────────────┘
                        │
        ┌───────────────┼───────────────┬──────────────┐
        ▼               ▼               ▼              ▼
┌────────────┐  ┌────────────┐  ┌──────────┐  ┌──────────────┐
│  Supabase  │  │ CloudFlare │  │   Novu   │  │  Edge        │
│  Database  │  │   Images   │  │  Cloud   │  │  Functions   │
│ PostgreSQL │  │  (direct)  │  │(webhooks)│  │   (Deno)     │
└────────────┘  └────────────┘  └──────────┘  └──────────────┘
```

---

## 🔄 Data Flow Architecture

### Entity Creation/Edit Flow (CRITICAL PATTERN)

```
1. User fills form → 2. Submission to moderation queue → 
3. Moderator reviews → 4. Edge function writes DB (service role) → 
5. Versioning trigger → 6. Entity live on site
```

**Rule #1: NEVER write directly to entity tables**

```typescript
// ❌ WRONG - Bypasses moderation, no versioning, no audit trail
await supabase.from('parks').insert(parkData);

// ✅ CORRECT - Goes through moderation queue
await submitParkCreation(parkData, user.id);
```

### Authentication Flow

```
1. User signs in (password/OAuth) → 2. Session established (AAL1) → 
3. Check MFA enrollment → 4. If enrolled: MFA challenge (AAL2) → 
5. Full access granted
```

---

## 🗄️ Core Principles

1. **NO JSONB for relational data** - All data properly normalized
2. **Metric-first storage** - All measurements in metric (km/h, m, cm, kg)
3. **Relational versioning** - Full history without JSONB
4. **RLS everywhere** - Row-Level Security on all tables
5. **Moderation-first** - Direct writes blocked, all through approval flow
6. **Calendar dates** - DATE type for dates, not TIMESTAMP (timezone-safe)
7. **Type safety** - TypeScript throughout, minimal `any` usage
8. **State machines** - Complex workflows managed by state machines

---

## 📚 Documentation Structure

### Architecture & Design
- **[ARCHITECTURE_OVERVIEW.md](./ARCHITECTURE_OVERVIEW.md)** (this file) - High-level system overview
- **[DATABASE_ARCHITECTURE.md](./DATABASE_ARCHITECTURE.md)** - Complete database schema and RLS patterns
- **[FRONTEND_ARCHITECTURE.md](./FRONTEND_ARCHITECTURE.md)** - React components, routing, state management
- **[AUTHENTICATION.md](./AUTHENTICATION.md)** - Auth methods, MFA, roles, session management

### Core Systems
- **[SUBMISSION_FLOW.md](./SUBMISSION_FLOW.md)** - Entity submission and moderation workflow
- **[IMAGE_UPLOAD_SYSTEM.md](./IMAGE_UPLOAD_SYSTEM.md)** - CloudFlare Images integration
- **[UNIT_SYSTEM.md](./UNIT_SYSTEM.md)** - Metric storage and display conversion
- **[DATE_HANDLING.md](./DATE_HANDLING.md)** - Timezone-safe date handling
- **[NOTIFICATION_SYSTEM.md](./NOTIFICATION_SYSTEM.md)** - Novu integration
- **[versioning/README.md](./versioning/README.md)** - Versioning system overview

### Implementation Details
- **[PHASE_4_IMPLEMENTATION.md](./PHASE_4_IMPLEMENTATION.md)** - State machine integration
- **[TYPE_SAFETY_MIGRATION.md](./TYPE_SAFETY_MIGRATION.md)** - TypeScript improvements
- **[JSONB_ELIMINATION.md](./JSONB_ELIMINATION.md)** - Database normalization journey

### Operations
- **[TESTING_GUIDE.md](./TESTING_GUIDE.md)** - Testing procedures and checklists
- **[DEPLOYMENT.md](./DEPLOYMENT.md)** - Deployment and environment setup
- **[TROUBLESHOOTING.md](./TROUBLESHOOTING.md)** - Common issues and solutions

---

## 🚦 System Status

### ✅ Production Ready
1. Authentication & Authorization (incl. MFA)
2. Moderation Queue & State Machine
3. Submission Flow (parks, rides, companies, models)
4. Versioning System (fully relational)
5. Image Upload (CloudFlare direct upload)
6. Unit System (metric storage, display conversion)
7. Date Handling (timezone-safe)
8. Notification System (Novu integration)
9. Lock Management (15-min locks with extension)
10. Type Safety (minimal `any` usage)

### 📋 Remaining Work
- Complete type safety migration (28 `as any` remaining)
- Unit validation in editors
- Integration testing
- Performance optimization
- User documentation

---

## 🔑 Quick Start

```bash
# Install dependencies
npm install

# Set up environment variables (see DEPLOYMENT.md)
cp .env.example .env

# Run development server
npm run dev

# Build for production
npm run build
```

---

## 📞 Support

For questions or issues:
1. Check relevant documentation file
2. Review code comments and types
3. Create GitHub issue with details

---

**Last Updated:** 2025-01-20  
**Version:** 1.0.0  
**Status:** 🟢 Production Ready
