# Authentication Setup Guide

## Overview
This guide sets up full server-side authentication for the TabataFit Admin panel.

## Prerequisites
- Supabase project running (local or hosted)
- Admin-web Next.js app running
- Database schema already applied

## Step 1: Configure Supabase Dashboard

1. Go to your Supabase Dashboard → Authentication → Providers
2. **Enable Email Provider**
3. **Disable "Confirm email"** (for easier testing, re-enable for production)
4. Go to Authentication → URL Configuration
5. Set **Site URL**: `http://localhost:3000` (or your production URL)
6. Add **Redirect URLs**: `http://localhost:3000/**`

## Step 2: Create Admin User

### Option A: Via Supabase Dashboard (Easiest)
1. Go to Supabase Dashboard → Authentication → Users
2. Click "Add user" or "Invite user"
3. Enter email: `admin@tabatafit.com`
4. Set password: Your chosen password
5. Click "Create user"
6. Copy the user's UUID (click on the user to see details)

### Option B: Via Login Page
1. Go to `http://localhost:3000/login`
2. Click "Sign up" (if available) or use dashboard method above

## Step 3: Add User to Admin Table

**Important**: After creating the user, you MUST add them to the admin_users table.

Run this SQL in Supabase SQL Editor:

```sql
-- Replace with your actual email or UUID
INSERT INTO public.admin_users (id, email, role)
SELECT id, email, 'admin'
FROM auth.users
WHERE email = 'admin@tabatafit.com'
ON CONFLICT (id) DO NOTHING;
```

Or if you have the UUID:
```sql
INSERT INTO public.admin_users (id, email, role) 
VALUES ('paste-uuid-here', 'admin@tabatafit.com', 'admin');
```

## Step 4: Verify Setup

Run this to confirm:
```sql
SELECT au.id, au.email, au.role, u.email as auth_email
FROM public.admin_users au
JOIN auth.users u ON au.id = u.id;
```

You should see your admin user listed.

## Step 5: Login

1. Go to `http://localhost:3000/login`
2. Enter email: `admin@tabatafit.com`
3. Enter password: (the one you set)
4. You should be redirected to the dashboard

## Troubleshooting

### "Not authorized as admin" error
- User exists in auth.users but not in admin_users table
- Run Step 3 SQL to add them

### "Failed to fetch" errors
- Check that EXPO_PUBLIC_SUPABASE_URL is set in .env.local
- For admin-web, also add NEXT_PUBLIC_SUPABASE_URL with same value

### Still can't create workouts
- Verify you're logged in (check browser cookies)
- Check that admin_users table has your user
- Check RLS policies are applied correctly

## Default Credentials (Example)

**Email**: `admin@tabatafit.com`
**Password**: (You choose during setup)

**Note**: Change this to a secure password in production!

## Security Notes

1. **Production**: Enable email confirmations
2. **Production**: Use strong passwords
3. **Production**: Enable 2FA if available
4. **Production**: Restrict CORS origins in Supabase
5. **Production**: Use environment-specific admin credentials