# EL3AB Backend Build Order

**Derived from:** Supabase Master Audit + Backend Architecture
**Approach:** Dependency-first, incremental, each module testable independently

---

## Build Order

### Module 1: Foundation & Config
**Dependencies:** None
**Complexity:** Low
**Files:**
- `config/database.php` — Supabase REST + direct PG constants
- `config/constants.php` — App URLs, keys, game constants
- `includes/supabase.php` — REST API helper class (GET/POST/PATCH/DELETE with auth)

**Tasks:**
1. Supabase REST client class (cURL-based)
2. Support for anon key (user context) and service key (admin context)
3. JWT token forwarding from client → Supabase
4. Error handling and response normalization

---

### Module 2: Authentication
**Dependencies:** Module 1
**Complexity:** Medium
**Tables:** auth.users, profiles
**Files:**
- `api/auth.php` — signup, login, logout, refresh
- `includes/auth_check.php` — session guard

**Tasks:**
1. Proxy signup to GoTrue `/auth/v1/signup`
2. Proxy login to GoTrue `/auth/v1/token?grant_type=password`
3. Token refresh endpoint
4. Logout (client-side token clear)
5. Server-side auth check utility

**Note:** Profile creation happens automatically via trigger — no need to handle in PHP.

---

### Module 3: Player Profile
**Dependencies:** Module 2
**Complexity:** Low
**Tables:** profiles, player_game_ratings
**Files:**
- `api/profile.php` — GET profile, PATCH update, avatar upload

**Tasks:**
1. Get own profile (with ratings)
2. Get other player's public profile
3. Update display_name, bio, country, language
4. Avatar upload via Supabase Storage
5. Get player_game_ratings for multi-game support

---

### Module 4: Chess Game (Core)
**Dependencies:** Module 2, Module 3
**Complexity:** High
**Tables:** matches, profiles (rating columns), player_game_ratings, rating_history
**Files:**
- `api/game.php` — start, move, resign, draw-offer, complete

**Tasks:**
1. Start match (INSERT matches with initial state)
2. Record move (UPDATE matches: moves jsonb, current_fen, timestamps)
3. Handle game endings (checkmate, stalemate, resign, timeout, draw)
4. Calculate Elo ratings on completion
5. Update profiles rating columns
6. Insert rating_history record
7. Award coins/XP
8. Update total_games/wins/losses/draws counters

---

### Module 5: Bot Integration
**Dependencies:** Module 4
**Complexity:** Low
**Tables:** matches (bot_id, bot_difficulty)
**Files:**
- `api/bots.php` — list bots, proxy move requests

**Tasks:**
1. Proxy GET /api/chess/bots from Stockfish API
2. Proxy POST /api/chess/move for bot responses
3. Start bot match with bot_id + bot_difficulty stored

---

### Module 6: Matchmaking
**Dependencies:** Module 4
**Complexity:** Medium
**Tables:** matchmaking_queue, matches
**Files:**
- `api/matchmaking.php` — queue, dequeue, match-found

**Tasks:**
1. Join queue (INSERT matchmaking_queue)
2. Leave queue (DELETE)
3. Find match (SELECT opponents within rating range)
4. Create match + update both queue entries
5. Rating range expansion over time logic
6. Handle expiry (max_wait_seconds)

---

### Module 7: Multiplayer Games (Domino + Ludo)
**Dependencies:** Module 2
**Complexity:** High
**Tables:** domino_matches, domino_queue, ludo_matches, ludo_queue
**Files:**
- `api/domino.php` — create/join/move/end
- `api/ludo.php` — create/join/roll/move/end

**Tasks:**
1. Create room (INSERT match with room_code)
2. Join room (UPDATE players jsonb array)
3. Matchmaking queue (insert/match/create-room)
4. Game moves (UPDATE board/positions/hands state)
5. Turn management (current_turn rotation)
6. Win detection and scoring
7. Game completion

---

### Module 8: Social
**Dependencies:** Module 2
**Complexity:** Low
**Tables:** friendships, notifications, chat_messages, activity_feed
**Files:**
- `api/friends.php` — request, accept, remove, list
- `api/notifications.php` — list, mark-read, unread-count

**Tasks:**
1. Send friend request (INSERT friendships status='pending')
2. Accept/reject (UPDATE status)
3. Remove friendship (DELETE)
4. List friends (SELECT where status='accepted')
5. List notifications (paginated)
6. Mark read (UPDATE is_read)
7. Unread count

---

### Module 9: Leaderboards & Ratings
**Dependencies:** Module 4
**Complexity:** Low
**Tables:** leaderboards, rating_history, player_game_ratings
**Files:**
- `api/leaderboard.php` — by game, time control, country
- `api/ratings.php` — history, calculate

**Tasks:**
1. Get leaderboard by game_key + time_control_type + period
2. Get player's rating history
3. Leaderboard refresh logic (cron or on-demand)

---

### Module 10: Economy & Shop
**Dependencies:** Module 2
**Complexity:** Medium
**Tables:** economy_transactions, cosmetics, player_cosmetics, profiles (coins/gems)
**Files:**
- `api/shop.php` — list, purchase, equip
- `api/daily-reward.php` — claim

**Tasks:**
1. List available cosmetics
2. Purchase (check balance, deduct, insert player_cosmetics, insert transaction)
3. Equip/unequip cosmetic
4. Daily reward claim (check last_daily_reward, update streak, award coins)
5. Transaction history

---

### Module 11: Achievements & XP
**Dependencies:** Module 4, Module 10
**Complexity:** Medium
**Tables:** achievements, player_achievements, xp_levels, profiles (xp/level)
**Files:**
- `api/achievements.php` — list, check-progress

**Tasks:**
1. List all achievements (with player progress)
2. Achievement check engine (called after game/event)
3. Award XP on achievement unlock
4. Level-up detection + rewards from xp_levels

---

### Module 12: Puzzles
**Dependencies:** Module 2
**Complexity:** Low
**Tables:** puzzles
**Files:**
- `api/puzzles.php` — random, by-rating, submit-solution

**Tasks:**
1. Get random puzzle (near player rating)
2. Get puzzle by ID
3. Submit solution (validate moves match)
4. Award XP/coins on solve

---

### Module 13: Tournaments (Player-Facing)
**Dependencies:** Module 4, Module 6
**Complexity:** Medium
**Tables:** el3ab_tournaments, tournament_registrations, tournament_brackets, bracket_matches
**Files:**
- `api/tournaments.php` — list, detail, register, cancel

**Tasks:**
1. List upcoming/active tournaments
2. Get tournament detail (with brackets + players)
3. Register (via RPC `register_tournament_player`)
4. Cancel registration (via RPC `cancel_tournament_registration`)
5. Get bracket/match state

---

### Module 14: Organizations (Player-Facing)
**Dependencies:** Module 2
**Complexity:** Medium
**Tables:** el3ab_organizations, org_members, org_invite_links
**Files:**
- `api/orgs.php` — list, detail, join, leave

**Tasks:**
1. List active organizations
2. Get org detail (members, stats)
3. Join via invite link
4. Leave organization
5. Org leaderboard

---

### Module 15: Analysis & Reporting
**Dependencies:** Module 4
**Complexity:** Low
**Tables:** matches (pgn, analysis_complete)
**Files:**
- `api/analysis.php` — request-analysis, get-analysis

**Tasks:**
1. Proxy game analysis to Stockfish API
2. Store analysis results
3. Get analysis for completed game

---

### Module 16: Theming
**Dependencies:** Module 1
**Complexity:** Low
**Tables:** theme_settings, game_theme_overrides, platform_theme
**Files:**
- `api/theme.php` — get theme for current context

**Tasks:**
1. Get platform default theme
2. Get game-specific overrides
3. Get org-specific overrides (if player in org)
4. Merge and return final theme tokens

---

---

## Risk Assessment

| Risk | Module | Mitigation |
|------|--------|-----------|
| Rating calculation bugs | 4 | Unit test Elo formula, use integer math |
| Race conditions in matchmaking | 6 | Use Supabase RLS + service key atomic ops |
| Realtime message ordering | 4, 7 | Client-side sequence validation |
| JSONB state corruption (domino/ludo) | 7 | Validate full state on each move server-side |
| Token expiry mid-game | 4 | Client-side refresh before expiry |
| Service key exposure | All | Never return in API responses, env-only |

---

## Technical Debt Awareness

1. **Dual org/tournament systems** — need clear routing logic to know which system to query
2. **Legacy profile columns** vs `player_game_ratings` — rating source needs normalization
3. **No backend triggers** — achievement checking must be explicitly called after events
4. **28 service_role-only tables** — org management requires privileged API endpoints
5. **Matchmaking is passive** — no active matcher; client must poll or use Realtime subscriptions
