# 🗄️ Supabase Integration Guide

*Seamless database operations with Mirror Magi Meta-Agent*

---

## 🎯 Overview

The meta-agent now supports **Supabase-specific task types** that ensure your database is properly configured before executing migrations or database operations.

**Enhanced workflow for Supabase:**
1. 🤖 **Generate** - AI creates plan with database tasks
2. 📝 **Structure** - Include Supabase-specific task types
3. ✅ **Validate** - Check Supabase setup automatically
4. 🎯 **Execute** - Get migration commands with pre-flight checks

---

## 🚀 Supabase Task Types

### `supabase_migration`
For database schema changes and migrations:

```json
{
  "id": "task_123",
  "description": "Add user_profiles table with avatar support",
  "type": "supabase_migration",
  "dependencies": [],
  "specifics": {
    "migrationName": "add_user_profiles",
    "tables": ["user_profiles"],
    "operations": ["create_table", "add_rls"],
    "requiresAuth": true
  }
}
```

### `supabase_function`
For Edge Functions:

```json
{
  "id": "task_124",
  "description": "Create email notification edge function",
  "type": "supabase_function",
  "dependencies": ["task_123"],
  "specifics": {
    "functionName": "send-email",
    "envVars": ["RESEND_API_KEY"],
    "triggers": ["user_profiles.insert"]
  }
}
```

### `supabase_rls`
For Row Level Security policies:

```json
{
  "id": "task_125",
  "description": "Add RLS policies for user_profiles",
  "type": "supabase_rls",
  "dependencies": ["task_123"],
  "specifics": {
    "table": "user_profiles",
    "policies": ["select", "update", "insert"],
    "authRequired": true
  }
}
```

---

## ✅ Automatic Pre-flight Checks

When you run `npm run plan:continue` with Supabase tasks, the system automatically:

### 1. **Environment Check**
```bash
✓ Checking Supabase CLI installation
✓ Verifying supabase project linked
✓ Checking database connection
✓ Validating environment variables
```

### 2. **Migration Safety**
```bash
✓ Checking for uncommitted migrations
✓ Validating migration naming
✓ Checking for conflicting schemas
✓ Backing up current schema
```

### 3. **Auth Verification**
```bash
✓ Checking auth configuration
✓ Validating JWT secrets
✓ Verifying email templates
```

---

## 📝 AI Prompt for Supabase Plans

Use this enhanced prompt:

```
I need a development plan for: [YOUR PROJECT WITH SUPABASE]

Please include database-specific tasks:

1. DATABASE SCHEMA
   - Tables needed with exact column names
   - Relationships between tables
   - RLS policies required
   - Indexes for performance

2. MIGRATIONS
   - Order of table creation
   - Data migration needs
   - Rollback strategies

3. EDGE FUNCTIONS
   - Function names and triggers
   - Environment variables needed
   - API integrations

4. VALIDATION
   - How to test migrations
   - Sample data requirements
   - RLS testing scenarios

Tech stack: Next.js, TypeScript, Supabase
```

---

## 🎯 Example Supabase Plan

```json
{
  "id": "plan_social_app",
  "goal": "Create social app with posts and comments using Supabase",
  "phases": [
    {
      "id": "phase_1",
      "name": "Database Foundation",
      "description": "Set up core database schema",
      "tasks": [
        {
          "id": "task_1",
          "description": "Create users and profiles tables with relationships",
          "type": "supabase_migration",
          "dependencies": [],
          "specifics": {
            "migrationName": "create_user_profiles",
            "tables": ["profiles"],
            "operations": ["create_table", "add_foreign_key"],
            "sql": "CREATE TABLE profiles (id uuid references auth.users primary key, username text unique not null, avatar_url text);"
          }
        },
        {
          "id": "task_2",
          "description": "Add RLS policies for profiles",
          "type": "supabase_rls",
          "dependencies": ["task_1"],
          "specifics": {
            "table": "profiles",
            "policies": ["users_can_view_all", "users_can_update_own"],
            "authRequired": true
          }
        }
      ]
    }
  ]
}
```

---

## 🚀 Execution with Claude Code Max

When executing Supabase tasks, you'll get commands like:

```bash
# The meta-agent generates:
"Claude Code Max, implement this Supabase migration:

PRE-FLIGHT CHECKS:
1. Run: supabase status (verify connection)
2. Run: supabase db diff (check for conflicts)
3. Run: git status (ensure clean state)

TASK: Create user_profiles table migration

IMPLEMENTATION:
1. Generate migration: supabase migration new create_user_profiles
2. Add SQL:
   ```sql
   CREATE TABLE profiles (
     id uuid references auth.users primary key,
     username text unique not null,
     avatar_url text,
     created_at timestamptz default now()
   );
   ```
3. Add RLS: ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;

VALIDATION:
1. Run: supabase db reset (test migration)
2. Check: SELECT * FROM profiles (verify structure)
3. Test: Insert sample data
4. Verify: RLS policies work correctly

SUCCESS CRITERIA:
- Migration applies without errors
- Table structure matches specification
- RLS policies prevent unauthorized access
- Can insert/select test data"
```

---

## 🛡️ Safety Features

### Automatic Rollback Commands
Every migration task includes rollback SQL:
```sql
-- Rollback for create_user_profiles
DROP TABLE IF EXISTS profiles CASCADE;
```

### Environment Isolation
```bash
# Development check
if [ "$SUPABASE_DB_URL" == *"localhost"* ]; then
  echo "✅ Safe: Using local database"
else
  echo "⚠️  Warning: Using remote database"
  read -p "Continue? (y/n) " -n 1 -r
fi
```

### Migration Versioning
```bash
# Automatic timestamp prefixing
20240601123456_create_user_profiles.sql
20240601123457_add_profiles_rls.sql
```

---

## 💡 Best Practices

### Plan Structure
1. **Group database tasks** in early phases
2. **Order migrations** by dependencies
3. **Include RLS** immediately after table creation
4. **Test migrations** before API integration

### Task Specifics
Always include:
- `migrationName` - Clear, descriptive names
- `tables` - All affected tables
- `operations` - What the migration does
- `rollback` - How to undo if needed

### Validation Steps
1. **Local first** - Always test on local Supabase
2. **Reset database** - Ensure migrations are idempotent
3. **Sample data** - Test with realistic data
4. **RLS testing** - Verify security policies

---

## 🔧 Configuration

Add to your project state for Supabase awareness:

```json
{
  "supabaseConfig": {
    "projectId": "your-project-id",
    "localUrl": "http://localhost:54321",
    "anonKey": "your-anon-key",
    "features": {
      "auth": true,
      "storage": true,
      "realtime": true,
      "edge_functions": true
    }
  }
}
```

---

## 🎯 Complete Workflow Example

1. **AI Prompt**:
   ```
   Create a blog with comments using Supabase, including proper RLS
   ```

2. **Structured Plan** includes:
   - `supabase_migration` tasks for schema
   - `supabase_rls` tasks for security
   - `api_integration` tasks for queries

3. **Validation** checks:
   - ✅ Supabase CLI installed
   - ✅ Project linked
   - ✅ Migration order logical

4. **Execution** provides:
   - Pre-flight safety checks
   - Exact migration SQL
   - Validation queries
   - Rollback procedures

---

*Safe, validated database operations with Mirror Magi + Supabase* 🚀 