# Clerk Authentication Setup Guide

This guide will walk you through setting up Clerk authentication for both the FitAI Admin (Next.js) and Mobile (Expo) applications.

## Prerequisites

- Node.js >= 18.0.0
- npm >= 9.0.0
- A Clerk account (sign up at https://clerk.com)

## Table of Contents

1. [Create a Clerk Application](#1-create-a-clerk-application)
2. [Admin App Setup (Next.js)](#2-admin-app-setup-nextjs)
3. [Mobile App Setup (Expo)](#3-mobile-app-setup-expo)
4. [Testing the Integration](#4-testing-the-integration)
5. [Troubleshooting](#5-troubleshooting)

---

## 1. Create a Clerk Application

### Step 1: Sign Up for Clerk

1. Go to https://dashboard.clerk.com
2. Sign up for a free account or sign in if you already have one

### Step 2: Create a New Application

1. Click "Add application" in the Clerk Dashboard
2. Choose a name for your application (e.g., "FitAI")
3. Select your authentication providers:
   - **Email** (required) - Enable email/password authentication
   - **Optional**: Google, Facebook, GitHub, etc.
4. Click "Create application"

### Step 3: Get Your API Keys

After creating your application, you'll see your API keys:

- **Publishable Key**: Starts with `pk_test_` (for development) or `pk_live_` (for production)
- **Secret Key**: Starts with `sk_test_` (for development) or `sk_live_` (for production)

**Important**: Keep your Secret Key secure and never commit it to version control!

---

## 2. Admin App Setup (Next.js)

### Step 1: Install Dependencies

The Clerk package is already installed. Verify with:

```bash
cd apps/admin
npm list @clerk/nextjs
```

### Step 2: Create Environment Variables

1. Create a `.env.local` file in `apps/admin/`:

```bash
cd apps/admin
cp .env.local.example .env.local
```

2. Edit `.env.local` and add your Clerk keys:

```env
# Clerk Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_PUBLISHABLE_KEY_HERE
CLERK_SECRET_KEY=sk_test_YOUR_SECRET_KEY_HERE

# Clerk URLs
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/

# Database
DATABASE_URL=./data/fitai.db
```

### Step 3: Configure Clerk Dashboard (Admin App)

In the Clerk Dashboard:

1. Go to **"Application"** → **"Paths"**
2. Set the following URLs:
   - **Sign-in URL**: `/sign-in` (or use Clerk's hosted pages)
   - **Sign-up URL**: `/sign-up` (or use Clerk's hosted pages)
   - **Home URL**: `/`

3. Go to **"Sessions"**
   - Enable "Multi-session handling" if you want users to have multiple sessions
   - Set session lifetime as needed (default: 7 days)

### Step 4: Test the Admin App

```bash
cd apps/admin
npm run dev
```

Visit http://localhost:3000 - you should be redirected to Clerk's sign-in page.

---

## 3. Mobile App Setup (Expo)

### Step 1: Install Dependencies

The Clerk Expo package and required dependencies are already installed. Verify with:

```bash
cd apps/mobile
npm list @clerk/clerk-expo expo-web-browser expo-auth-session expo-secure-store expo-crypto
```

**Note**: If you need to install manually:
```bash
npm install @clerk/clerk-expo expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web
```

**All Required Clerk Dependencies:**
- `@clerk/clerk-expo` - Core Clerk SDK
- `expo-web-browser` - OAuth flows and browser interactions
- `expo-auth-session` - SSO and authentication sessions
- `expo-secure-store` - Secure token storage
- `expo-crypto` - Cryptographic functions
- `react-dom` - React DOM for web compatibility
- `react-native-web` - React Native web compatibility layer
- `expo-constants` - App configuration (already installed)
- `expo-linking` - Deep linking support (already installed)

### Step 2: Create Environment Variables

1. Create a `.env` file in `apps/mobile/`:

```bash
cd apps/mobile
cp .env.example .env
```

2. Edit `.env` and add your Clerk publishable key:

```env
# Clerk Authentication
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_PUBLISHABLE_KEY_HERE

# API Configuration
EXPO_PUBLIC_API_URL=http://localhost:3000/api

# App Configuration
EXPO_PUBLIC_APP_NAME=FitAI
EXPO_PUBLIC_APP_VERSION=1.0.0
```

**Note**: For mobile apps, you only need the publishable key (not the secret key).

### Step 3: Configure Clerk Dashboard (Mobile App)

In the Clerk Dashboard:

1. Go to **"Application"** → **"Mobile"**
2. Add your app's package/bundle identifiers:
   - **Android**: `com.fitai.mobile` (or your custom package name)
   - **iOS**: `com.fitai.mobile` (or your custom bundle ID)

3. Go to **"Email, Phone, Username"** settings:
   - Enable **Email address** as a required identifier
   - Enable **Password** as a required authentication strategy
   - Optional: Enable **Email verification code** for passwordless login

### Step 4: Update App Configuration

Edit `apps/mobile/app.json` to ensure your package names match Clerk configuration:

```json
{
  "expo": {
    "name": "FitAI",
    "slug": "fitai-mobile",
    "version": "1.0.0",
    "ios": {
      "bundleIdentifier": "com.fitai.mobile"
    },
    "android": {
      "package": "com.fitai.mobile"
    }
  }
}
```

### Step 5: Test the Mobile App

```bash
cd apps/mobile
npm start
```

Use Expo Go to scan the QR code and test the app on your device.

---

## 4. Testing the Integration

### Admin App Testing

1. **Start the admin app**:
   ```bash
   cd apps/admin
   npm run dev
   ```

2. **Test Sign-Up**:
   - Visit http://localhost:3000
   - You'll be redirected to Clerk's sign-in page
   - Click "Sign up" and create a test account
   - Complete email verification (check your inbox)
   - You should be redirected to the dashboard

3. **Test Sign-In**:
   - Sign out using the user button in the header
   - Sign back in with your credentials
   - Verify you can access protected routes

### Mobile App Testing

1. **Start the mobile app**:
   ```bash
   cd apps/mobile
   npm start
   ```

2. **Test Sign-Up**:
   - Open the app in Expo Go
   - Tap "Sign Up" on the welcome screen
   - Fill in your details (use a different email than admin)
   - Enter the verification code sent to your email
   - You should be redirected to the home tab

3. **Test Sign-In**:
   - Sign out from the Profile tab
   - Sign back in with your credentials
   - Verify navigation works correctly

### Cross-Platform Testing

Test that both apps work together:

1. Create a user in the admin app
2. Try logging in with the same credentials in the mobile app
3. Verify user data syncs across platforms

---

## 5. Troubleshooting

### Common Issues and Solutions

#### Issue: "Missing Clerk Publishable Key"

**Solution**: 
- Ensure your `.env.local` (admin) or `.env` (mobile) file exists
- Verify the key starts with `pk_test_` or `pk_live_`
- Restart your development server after adding the key

#### Issue: "Invalid API key"

**Solution**:
- Double-check your keys in the Clerk Dashboard
- Make sure you're using the correct environment (test vs. production)
- Ensure there are no extra spaces or quotes in your `.env` file

#### Issue: Mobile app shows blank screen

**Solution**:
- Check the console logs for errors
- Verify `@clerk/clerk-expo` is installed correctly
- Ensure `expo-secure-store` is installed (required for token storage)
- Ensure `expo-web-browser` is installed (required for OAuth flows)
- Try clearing Expo cache: `npx expo start -c`

#### Issue: "Unable to resolve expo-web-browser", "expo-auth-session", or "react-dom"

**Solution**:
Install all required Clerk dependencies at once:
```bash
cd apps/mobile
npm install expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web
npx expo start -c
```

These packages are required by Clerk for:
- `expo-web-browser` - OAuth authentication flows
- `expo-auth-session` - SSO and session management
- `expo-secure-store` - Secure token storage
- `expo-crypto` - Cryptographic operations
- `react-dom` - React DOM for web compatibility
- `react-native-web` - React Native web compatibility layer

#### Issue: Email verification code not received

**Solution**:
- Check your spam folder
- In Clerk Dashboard, verify email settings are configured
- For development, you can check the Clerk Dashboard logs to see sent emails
- Consider enabling "Development mode" in Clerk to bypass email verification

#### Issue: Redirect loops or infinite redirects

**Solution**:
- Check your middleware configuration in `apps/admin/src/middleware.ts`
- Ensure public routes are properly defined
- Verify `NEXT_PUBLIC_CLERK_SIGN_IN_URL` is set correctly
- Clear browser cookies and try again

#### Issue: "ERESOLVE" errors during npm install

**Solution**:
- Use `--legacy-peer-deps` flag:
  ```bash
  npm install --legacy-peer-deps
  ```
- This is normal for React Native projects with multiple dependencies

#### Issue: Bundling failed with Clerk dependencies

**Solution**:
- Ensure all required Expo packages are installed:
  ```bash
  cd apps/mobile
  npm install expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web expo-constants
  ```
- Clear Metro bundler cache:
  ```bash
  npx expo start -c
  ```
- Verify all dependencies:
  ```bash
  npm list @clerk/clerk-expo
  ```

---

## Advanced Configuration

### Customizing Clerk UI

You can customize Clerk's appearance in both apps:

**Admin App** (`apps/admin/src/app/layout.tsx`):
```tsx
<ClerkProvider
  appearance={{
    baseTheme: "light",
    variables: {
      colorPrimary: "#2563eb",
      fontFamily: "Inter, sans-serif",
    },
  }}
>
```

**Mobile App**: Use custom screens (already implemented in `apps/mobile/src/app/(auth)/`)

### Adding Social Providers

1. In Clerk Dashboard, go to **"Social Connections"**
2. Enable providers (Google, Facebook, etc.)
3. Add OAuth credentials for each provider
4. No code changes needed - Clerk handles it automatically!

### Webhooks (Optional)

To sync Clerk users with your database:

1. In Clerk Dashboard, go to **"Webhooks"**
2. Add endpoint: `https://your-domain.com/api/webhooks/clerk`
3. Select events: `user.created`, `user.updated`, `user.deleted`
4. Implement webhook handler in `apps/admin/src/app/api/webhooks/clerk/route.ts`

### Multi-tenant Support

For gym chains with multiple locations:

1. Use Clerk Organizations feature
2. Enable in Clerk Dashboard under **"Organizations"**
3. Each gym becomes an organization
4. Users can belong to multiple organizations

---

## Security Best Practices

1. **Never commit `.env` files** - They're in `.gitignore` by default
2. **Use different keys for development and production**
3. **Enable MFA** for admin accounts in Clerk Dashboard
4. **Set up rate limiting** for API routes
5. **Regularly rotate API keys** in production
6. **Use HTTPS** in production (required for OAuth)
7. **Enable session security features** in Clerk Dashboard

---

## Next Steps

After successfully setting up Clerk:

1. ✅ Test authentication flows in both apps
2. ✅ Customize the sign-in/sign-up experience
3. ✅ Set up user roles and permissions
4. 🔄 Implement payment system integration
5. 🔄 Add attendance tracking with Clerk user IDs
6. 🔄 Set up webhook handlers for user sync
7. 🔄 Configure production environment variables
8. 🔄 Deploy to production with proper SSL/HTTPS

---

## Resources

- **Clerk Documentation**: https://clerk.com/docs
- **Next.js Integration Guide**: https://clerk.com/docs/quickstarts/nextjs
- **Expo Integration Guide**: https://clerk.com/docs/quickstarts/expo
- **Clerk Dashboard**: https://dashboard.clerk.com
- **Clerk Discord Community**: https://clerk.com/discord

---

## Support

If you encounter issues not covered in this guide:

1. Check the [Clerk documentation](https://clerk.com/docs)
2. Search [Clerk's Discord community](https://clerk.com/discord)
3. Review the [troubleshooting section](#5-troubleshooting) above
4. Check the console logs for detailed error messages

---

**Last Updated**: January 2025  
**Version**: 1.0.1  
**Clerk SDK Versions**:
- `@clerk/nextjs`: Latest
- `@clerk/clerk-expo`: Latest

**Required Dependencies for Mobile**:
- `expo-web-browser`: OAuth flows and browser interactions
- `expo-auth-session`: SSO and authentication sessions
- `expo-secure-store`: Secure token storage
- `expo-crypto`: Cryptographic functions
- `react-dom`: React DOM for web compatibility
- `react-native-web`: React Native web compatibility layer
- `expo-constants`: App configuration
- `expo-linking`: Deep linking support
- `expo-status-bar`: Status bar styling (optional)