# 📊 Visual Guide - Supabase Setup Flow

Panduan visual untuk memudahkan memahami flow setup Supabase.

---

## 🎯 Architecture Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                        YOUR BROWSER                              │
│  http://localhost:3000/game (Next.js App)                        │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │ • Dashboard                                                   │ │
│  │ • Game                                                        │ │
│  │ • Quiz                                                        │ │
│  │ • Videos                                                      │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
                              ↓
                    (via .env.local)
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                    SUPABASE (Cloud)                              │
│  https://xxxxx.supabase.co                                       │
│  ┌─────────────────────────────────────────────────────────────┐ │
│  │                  PostgreSQL Database                         │ │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐       │ │
│  │  │  profiles    │  │  game_       │  │  quizzes     │       │ │
│  │  │  table       │  │  sessions    │  │  table       │       │ │
│  │  │              │  │  table       │  │              │       │ │
│  │  │ • username   │  │ • score      │  │ • questions  │  ...  │ │
│  │  │ • email      │  │ • user_id    │  │ • answers    │       │ │
│  │  │ • points     │  │ • timestamp  │  │ • status     │       │ │
│  │  └──────────────┘  └──────────────┘  └──────────────┘       │ │
│  │                                                              │ │
│  │  Authentication (Auth Service)                              │ │
│  │  ┌──────────────────────────────────────────────────────┐  │ │
│  │  │ Users dapat login/register dengan email & password   │  │ │
│  │  │ Session management otomatis                          │  │ │
│  │  └──────────────────────────────────────────────────────┘  │ │
│  └─────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```

---

## 📋 Setup Process Flow

```
START
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 1: Create Supabase Account                 │
│ • Go to https://supabase.com                    │
│ • Sign up with Email/GitHub/Google              │
│ • Verify email                                   │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 2: Create Project                          │
│ • Project name: ecolearn_db                     │
│ • Region: Singapore (recommended)               │
│ • Plan: Free Tier                               │
│ • Get: Database Password (SAVE THIS!)           │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 3: Copy Credentials                        │
│ • Go to Project Settings → API                  │
│ • Copy URL                                       │
│ • Copy anon key                                  │
│ • Copy service_role key                         │
│ • Save to notepad                               │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 4: Update .env.local                       │
│ • File: Website-Pemilahan-Sampah/.env.local    │
│ • Paste credentials:                            │
│   - NEXT_PUBLIC_SUPABASE_URL                    │
│   - NEXT_PUBLIC_SUPABASE_ANON_KEY               │
│   - SUPABASE_SERVICE_ROLE_KEY                   │
│ • Save file                                      │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 5: Run SQL Schema                          │
│ • Go to Supabase → SQL Editor                   │
│ • Open: SQL_SCHEMA_SETUP.sql                    │
│ • Copy all & paste to SQL Editor                │
│ • Click "Run"                                    │
│ • Wait for success                               │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 6: Verify Tables Created                   │
│ • Go to Database → Tables                       │
│ • Check if 13 tables exist:                     │
│   profiles, videos, game_sessions, etc.        │
│ • All there? ✅                                  │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 7: Restart Next.js                         │
│ • Terminal: Ctrl+C (stop old server)            │
│ • Run: npm run dev                              │
│ • Wait: "Ready in X.Xs"                         │
│ • No errors? ✅                                  │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 8: Test Signup                             │
│ • Browser: http://localhost:3000                │
│ • Click "Sign Up"                               │
│ • Email: test@example.com                       │
│ • Password: TestPassword123!                    │
│ • Success? ✅                                    │
│ • Check Supabase → Database → profiles          │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 9: Test Login                              │
│ • Click "Logout" first                          │
│ • Then click "Login"                            │
│ • Same email & password                         │
│ • Success? ✅                                    │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ STEP 10: Test Points System                     │
│ • Go to http://localhost:3000/game              │
│ • Click "Simulasi Bermain"                      │
│ • Points increase? ✅                            │
│ • Refresh page                                   │
│ • Points still there? ✅                         │
└─────────────────────────────────────────────────┘
  ↓
┌─────────────────────────────────────────────────┐
│ 🎉 SETUP COMPLETE!                              │
│ Ready for Week 2: API Implementation            │
└─────────────────────────────────────────────────┘
```

---

## 🔑 Where to Find Credentials

### Browser Location 1: Dashboard Home
```
https://app.supabase.com
         ↓
    [Choose ecolearn_db project]
         ↓
    Left Sidebar → Project Settings
         ↓
    Tab: "API"
         ↓
    ✓ Find: Project URL
    ✓ Find: anon key
    ✓ Find: service_role key
```

### Browser Location 2: Direct URL
```
https://app.supabase.com/project/[project-id]/settings/api
                                              ↓
                              (Langsung ke API page)
```

---

## 📁 File Locations

```
Website-Pemilahan-Sampah/
├─ .env.local ← UPDATE INI
│  ├─ NEXT_PUBLIC_SUPABASE_URL
│  ├─ NEXT_PUBLIC_SUPABASE_ANON_KEY
│  └─ SUPABASE_SERVICE_ROLE_KEY
│
├─ lib/
│  ├─ supabase/
│  │  ├─ client.ts ← Uses .env.local
│  │  ├─ server.ts
│  │  └─ types.ts
│  └─ hooks/
│     ├─ useAuth.ts ← Checks login status
│     ├─ usePoints.ts ← Saves points IF logged in
│     └─ useProfile.ts
│
├─ SQL_SCHEMA_SETUP.sql ← JALANKAN INI di Supabase
│
├─ SUPABASE_SETUP_GUIDE.md ← BACA INI untuk detail
│
├─ SETUP_CHECKLIST.md ← IKUTI CHECKLIST INI
│
└─ CREDENTIALS_TEMPLATE.txt ← SIMPAN credentials di sini
```

---

## 🔄 Data Flow: User Login → Game → Save Points

```
USER ACTION:
"User clicks Sign Up"
         ↓
┌─────────────────────────────────────────┐
│ BROWSER (Next.js App)                   │
│ LoginForm.tsx                           │
│ • Collect email & password              │
│ • Call: supabaseClient.auth.signUp()    │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ NETWORK                                  │
│ POST request to Supabase Auth API        │
│ { email, password }                      │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ SUPABASE (Cloud)                        │
│ Auth Service                            │
│ • Validate credentials                  │
│ • Create user in auth.users             │
│ • Return: JWT session token             │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ SUPABASE Trigger                        │
│ on_auth_user_created                    │
│ • Automatically create profile record   │
│ • Set: id, email, username              │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ BROWSER (Next.js App)                   │
│ useAuth hook detects new user           │
│ • Redirect to /dashboard                │
│ • Show normal content (no warning)      │
└─────────────────────────────────────────┘


====== USER PLAYS GAME ======


USER ACTION:
"User clicks 'Simulasi Bermain & Dapatkan Poin'"
         ↓
┌─────────────────────────────────────────┐
│ BROWSER (Next.js App)                   │
│ GamePage.tsx                            │
│ • Call: addPoints(score, 'game_play')   │
│ • usePoints hook                        │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ LOCAL CHECK                             │
│ if (user) {                             │
│   // Logged in: Save to DB              │
│ } else {                                │
│   // Not logged in: Local state only    │
│ }                                       │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ IF LOGGED IN:                           │
│ NETWORK                                  │
│ POST /api/games                         │
│ { score, reason, totalPoints }          │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ BROWSER (Next.js App)                   │
│ /api/games route handler                │
│ • Validate session                      │
│ • Call DB: INSERT into game_sessions    │
│ • Call DB: UPDATE profiles.total_points │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ SUPABASE Database                       │
│ UPDATE profiles                         │
│ SET total_points = total_points + 25    │
│ WHERE id = user_id                      │
│                                         │
│ INSERT INTO game_sessions               │
│ (user_id, score, game_type, ...)        │
└─────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────┐
│ BROWSER (Next.js App)                   │
│ UI Updates:                             │
│ • Show: "+25 points earned!"            │
│ • Display: New total points             │
└─────────────────────────────────────────┘
         ↓
USER REFRESHES PAGE
         ↓
┌─────────────────────────────────────────┐
│ BROWSER (Next.js App)                   │
│ useProfile hook                         │
│ • Fetch profiles WHERE id = user_id     │
│ • Get latest total_points from DB       │
│ • Display on dashboard                  │
└─────────────────────────────────────────┘
```

---

## 🔐 Security: RLS (Row Level Security)

```
WITHOUT RLS:
┌─────────────────────────────┐
│ Database (Anyone can read)  │
│ User A:                     │
│ • Points: 500              │
│ • Email: a@email.com       │
│                             │
│ User B:                     │
│ • Points: 300              │
│ • Email: b@email.com       │
│                             │
│ User C can access ALL data! │
│ ❌ NOT SECURE               │
└─────────────────────────────┘


WITH RLS (AMAN):
┌─────────────────────────────────────┐
│ Database (WITH RLS Policies)        │
│                                     │
│ User A (logged in as A):            │
│ Query: SELECT * FROM profiles       │
│ Result: ✅ Can see own profile      │
│         ❌ Cannot see B's profile   │
│                                     │
│ User B (logged in as B):            │
│ Query: SELECT * FROM profiles       │
│ Result: ✅ Can see own profile      │
│         ❌ Cannot see A's profile   │
│                                     │
│ User C (not logged in):             │
│ Query: SELECT * FROM profiles       │
│ Result: ❌ No data returned         │
│                                     │
│ ✅ SECURE - Data protected!         │
└─────────────────────────────────────┘
```

---

## ⏰ Estimated Timeline

```
Activity                    Time
─────────────────────────────────────
1. Create account            2 min
2. Create project            5 min (+ waiting)
3. Copy credentials          3 min
4. Update .env.local         2 min
5. Run SQL schema            5 min
6. Verify tables             3 min
7. Restart server            3 min
8. Test signup               5 min
9. Test login                3 min
10. Test points              5 min
─────────────────────────────────────
   TOTAL                    ~40 min
```

---

## ✅ Success Indicators

### Phase 1: Account Created ✓
```
✓ Can login to https://app.supabase.com
✓ Can see dashboard
```

### Phase 2: Project Created ✓
```
✓ Project "ecolearn_db" exists
✓ Status shows "Active" (not "Creating")
✓ Can access SQL Editor
```

### Phase 3: Credentials Ready ✓
```
✓ NEXT_PUBLIC_SUPABASE_URL has value
✓ NEXT_PUBLIC_SUPABASE_ANON_KEY has value
✓ SUPABASE_SERVICE_ROLE_KEY has value
```

### Phase 4: Schema Ready ✓
```
✓ 13 tables visible in Database → Tables
✓ Each table has columns (not empty)
✓ Indexes created (shown in table detail)
✓ RLS enabled (shown in Security tab)
```

### Phase 5: App Connected ✓
```
✓ npm run dev shows "Ready in Xs"
✓ No environment variable errors
✓ http://localhost:3000 loads without errors
```

### Phase 6: Auth Working ✓
```
✓ Can sign up new user
✓ Email verification works
✓ User data in profiles table
✓ Can login
✓ Session is set (cookie visible in DevTools)
```

### Phase 7: Points Working ✓
```
✓ Can increment points (UI shows +25)
✓ Refresh page → points persist
✓ Data visible in game_sessions table
✓ profiles.total_points updated
```

---

## 🎓 What You've Learned

```
After this setup, you should understand:

✓ What Supabase is (BaaS platform)
✓ How PostgreSQL database works (tables, relationships)
✓ How authentication flows (signup → verify → login)
✓ How to use SQL (CREATE TABLE, INSERT, SELECT)
✓ How RLS protects data (Row Level Security)
✓ How environment variables work
✓ How Next.js connects to backend (via .env)
✓ How data flows from UI → API → Database

You're now ready for Week 2! 🚀
```

---

**Created:** August 14, 2026  
**Version:** 1.0.0
