# Supabase Integration Guide

## ✅ Setup Complete

You've successfully:
- ✅ Logged into Supabase CLI
- ✅ Initialized Supabase in your project
- ✅ Installed Supabase JavaScript client
- ✅ Created migration files

## 🚀 Next Steps

### 1. Link to Your Supabase Project

If you have an existing project:
```bash
supabase link --project-ref your-project-ref
```

Or create a new project:
```bash
supabase projects create your-project-name
```

### 2. Configure Environment Variables

Get your Supabase credentials from: https://supabase.com/dashboard/project/_/settings/api

Then update `.env.supabase`:
```bash
cp .env.supabase .env

# Edit with your values:
SUPABASE_URL=https://your-project-ref.supabase.co
SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
DATABASE_URL=postgresql://postgres:[PASSWORD]@db.your-project-ref.supabase.co:5432/postgres
```

### 3. Push Database Migrations

```bash
# Push your domain verification schema to Supabase
supabase db push
```

Or run migrations manually:
```bash
# Apply all migrations
supabase db push

# Or connect and run SQL directly
supabase db reset
```

### 4. Start Local Development

**Option A: Use Remote Supabase Database**
```bash
# Backend will connect to your Supabase project
npm run dev
```

**Option B: Local Supabase (Docker required)**
```bash
# Start local Supabase stack
supabase start

# This gives you:
# - Local PostgreSQL database
# - Local Auth server
# - Local API
# - Studio UI at http://localhost:54323

# Then start your backend
npm run dev
```

### 5. Frontend Configuration

Update your frontend to use Supabase auth (optional):

```javascript
// src/frontend/utils/supabase.js
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.VITE_SUPABASE_URL,
  process.env.VITE_SUPABASE_ANON_KEY
)

export { supabase }
```

## 📋 Available Commands

```bash
# Project Management
supabase projects list              # List all projects
supabase link                       # Link to a project
supabase status                     # Check connection status

# Database
supabase db push                    # Push migrations to remote
supabase db reset                   # Reset local database
supabase db diff                    # Show schema differences
supabase migration new <name>       # Create new migration

# Local Development
supabase start                      # Start local Supabase
supabase stop                       # Stop local Supabase
supabase status                     # Check local services

# Functions (for future use)
supabase functions new <name>       # Create Edge Function
supabase functions deploy <name>    # Deploy Edge Function
```

## 🔄 Database Schema

Your domain verification tables are ready to deploy:

```
supabase/migrations/
└── 20260110025404_domain_verifications.sql
```

This includes:
- `domain_verifications` table
- `users` table extensions
- Indexes for performance

## 🎯 Integration Options

### Option 1: Use Supabase Auth (Recommended)

Replace custom JWT with Supabase Auth:
- Built-in authentication
- User management UI
- Social auth providers
- Row Level Security (RLS)

### Option 2: Keep Custom Auth

Continue using your custom JWT auth and just use Supabase as the database.

## 🔒 Security: Row Level Security (RLS)

Add RLS policies to your tables for extra security:

```sql
-- Enable RLS on domain_verifications
ALTER TABLE domain_verifications ENABLE ROW LEVEL SECURITY;

-- Users can only see their own verifications
CREATE POLICY "Users can view own verifications"
  ON domain_verifications FOR SELECT
  USING (auth.uid()::text = user_id);

-- Users can only insert their own verifications
CREATE POLICY "Users can insert own verifications"
  ON domain_verifications FOR INSERT
  WITH CHECK (auth.uid()::text = user_id);
```

## 📊 Database Access

### Via Supabase Studio
https://supabase.com/dashboard/project/_/editor

### Via CLI
```bash
supabase db remote
```

### Via Direct Connection
Use the DATABASE_URL from your `.env` file with any PostgreSQL client.

## 🧪 Testing

Test your Supabase connection:
```bash
# Check if you can connect
supabase db remote exec "SELECT version();"

# List tables
supabase db remote exec "SELECT tablename FROM pg_tables WHERE schemaname = 'public';"
```

## 📝 Migration Workflow

1. Make schema changes locally
2. Generate migration:
   ```bash
   supabase db diff -f new_migration_name
   ```
3. Review the generated SQL
4. Push to production:
   ```bash
   supabase db push
   ```

## 🚨 Troubleshooting

**Connection Failed**
```bash
# Check if linked
supabase status

# Relink if needed
supabase link --project-ref your-project-ref
```

**Migration Errors**
```bash
# View migration status
supabase migration list

# Reset if needed (⚠️ destructive)
supabase db reset
```

**Local Development Issues**
```bash
# Check Docker is running
docker ps

# Restart Supabase
supabase stop
supabase start
```

## 🔗 Useful Links

- **Dashboard**: https://supabase.com/dashboard
- **Docs**: https://supabase.com/docs
- **CLI Reference**: https://supabase.com/docs/reference/cli
- **API Docs**: https://supabase.com/docs/reference/javascript

---

**Ready to deploy?** Run `supabase db push` to apply your schema! 🚀
