# Google Classroom Integration Setup Guide

**Goal:** Set up Google Classroom API integration using mostly CLI commands, minimizing web console interaction.

**Time Required:** 15-20 minutes
**Cost:** $0 (free for educational use)

---

## Prerequisites

✅ **gcloud CLI installed** (already installed at `/opt/homebrew/bin/gcloud`)
✅ **Valid Google account**
- **Billing account** (required by Google, but FREE for Classroom API)

---

## Quick Start (TL;DR)

```bash
# Run the automated setup script
./scripts/setup-google-classroom.sh
```

The script will:
1. Authenticate with your Google account
2. Create a GCP project
3. Enable Classroom & People APIs
4. Guide you through OAuth setup (2 web console steps)
5. Configure your `.env.local` file

**Note:** Steps 6 & 7 still require web console (Google doesn't provide CLI for OAuth consent screen), but the script opens the pages for you and provides exact instructions.

---

## What the Script Does (Step by Step)

### 1. Authentication ✅ Fully Automated
```bash
gcloud auth login
```
Opens browser, you log in with Google, done.

### 2. Create GCP Project ✅ Fully Automated
```bash
PROJECT_ID="soroban-abacus-$(date +%s)"  # Unique ID with timestamp
gcloud projects create "$PROJECT_ID" --name="Soroban Abacus Flashcards"
gcloud config set project "$PROJECT_ID"
```

### 3. Link Billing Account ✅ Mostly Automated
```bash
# List your billing accounts
gcloud billing accounts list

# Link to project
gcloud billing projects link "$PROJECT_ID" --billing-account="BILLING_ACCOUNT_ID"
```

**Why billing is required:**
- Google requires billing for API access (even free APIs!)
- Classroom API is **FREE** with no usage charges
- You won't be charged unless you enable paid services

**If you don't have a billing account:**
- Script will prompt you to create one at: https://console.cloud.google.com/billing
- It's quick: just add payment method (won't be charged)
- Press Enter in terminal after creation

### 4. Enable APIs ✅ Fully Automated
```bash
gcloud services enable classroom.googleapis.com
gcloud services enable people.googleapis.com
```

Takes 1-2 minutes to propagate.

### 5. Create OAuth Credentials ⚠️ Requires Web Console

**Why CLI doesn't work:**
Google doesn't provide `gcloud` commands for creating OAuth clients. You need the web console.

**What the script does:**
- Opens: https://console.cloud.google.com/apis/credentials?project=YOUR_PROJECT
- Provides exact instructions (copy-paste ready)

**Manual steps (takes 2 minutes):**
1. Click "**Create Credentials**" → "**OAuth client ID**"
2. Application type: **"Web application"**
3. Name: **"Soroban Abacus Web"**
4. **Authorized JavaScript origins:**
   ```
   http://localhost:3000
   https://abaci.one
   ```
5. **Authorized redirect URIs:**
   ```
   http://localhost:3000/api/auth/callback/google
   https://abaci.one/api/auth/callback/google
   ```
6. Click **"Create"**
7. **Copy** the Client ID and Client Secret (you'll paste into terminal)

### 6. Configure OAuth Consent Screen ⚠️ Requires Web Console

**Why CLI doesn't work:**
OAuth consent screen configuration is web-only.

**What the script does:**
- Opens: https://console.cloud.google.com/apis/credentials/consent?project=YOUR_PROJECT
- Provides step-by-step instructions

**Manual steps (takes 3 minutes):**

**Screen 1: OAuth consent screen**
- User Type: **"External"** (unless you have Google Workspace)
- Click "**Create**"

**Screen 2: App information**
- App name: **"Soroban Abacus Flashcards"**
- User support email: **Your email**
- App logo: (optional)
- App domain: (optional, can add later)
- Developer contact: **Your email**
- Click "**Save and Continue**"

**Screen 3: Scopes**
- Click "**Add or Remove Scopes**"
- Filter/search for these scopes and check them:
  - ✅ `.../auth/userinfo.email` (See your primary Google Account email)
  - ✅ `.../auth/userinfo.profile` (See your personal info)
  - ✅ `.../auth/classroom.courses.readonly` (View courses)
  - ✅ `.../auth/classroom.rosters.readonly` (View class rosters)
- Click "**Update**"
- Click "**Save and Continue**"

**Screen 4: Test users**
- Click "**Add Users**"
- Add your email address (for testing)
- Click "**Save and Continue**"

**Screen 5: Summary**
- Review and click "**Back to Dashboard**"

Done! ✅

### 7. Save Credentials to .env.local ✅ Fully Automated

Script prompts you for:
- Client ID (paste from step 5)
- Client Secret (paste from step 5)

Then automatically adds to `.env.local`:
```bash
# Google OAuth (Generated by setup-google-classroom.sh)
GOOGLE_CLIENT_ID="your-client-id.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="GOCSPX-your-secret"
```

---

## After Running the Script

### Verify Setup

```bash
# Check project configuration
gcloud config get-value project

# List enabled APIs
gcloud services list --enabled

# Check Classroom API is enabled
gcloud services list --enabled | grep classroom
```

Expected output:
```
classroom.googleapis.com          Google Classroom API
```

### Test API Access

```bash
# Get an access token
gcloud auth application-default login
gcloud auth application-default print-access-token

# Test Classroom API (replace TOKEN)
curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://classroom.googleapis.com/v1/courses
```

Expected response (if you have no courses yet):
```json
{}
```

---

## NextAuth Configuration

Now that you have credentials, add Google provider to NextAuth:

### 1. Check Current NextAuth Config

```bash
cat src/app/api/auth/[...nextauth]/route.ts
```

### 2. Add Google Provider

Add to your NextAuth providers array:

```typescript
import GoogleProvider from "next-auth/providers/google"

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      authorization: {
        params: {
          scope: [
            'openid',
            'email',
            'profile',
            'https://www.googleapis.com/auth/classroom.courses.readonly',
            'https://www.googleapis.com/auth/classroom.rosters.readonly',
          ].join(' '),
          prompt: 'consent',
          access_type: 'offline',
          response_type: 'code'
        }
      }
    }),
    // ... your existing providers
  ],
  // ... rest of config
}
```

### 3. Test Login

```bash
# Start dev server
npm run dev

# Open browser
open http://localhost:3000
```

Click "Sign in with Google" and verify:
- ✅ OAuth consent screen appears
- ✅ Shows requested permissions
- ✅ Successfully logs in
- ✅ User profile is created

---

## Troubleshooting

### "Billing account required"

**Problem:** Can't enable APIs without billing
**Solution:** Create billing account at https://console.cloud.google.com/billing
- Won't be charged for Classroom API (it's free)
- Just need payment method on file

### "Error 401: deleted_client"

**Problem:** OAuth client was deleted or not created properly
**Solution:** Re-run OAuth client creation (step 5)
```bash
open "https://console.cloud.google.com/apis/credentials?project=$(gcloud config get-value project)"
```

### "Error 403: Access Not Configured"

**Problem:** APIs not enabled yet (takes 1-2 min to propagate)
**Solution:** Wait 2 minutes, then verify:
```bash
gcloud services list --enabled | grep classroom
```

### "Invalid redirect URI"

**Problem:** Redirect URI doesn't match OAuth client config
**Solution:** Check that these URIs are in your OAuth client:
- http://localhost:3000/api/auth/callback/google
- https://abaci.one/api/auth/callback/google

### "App is not verified"

**Problem:** OAuth consent screen in "Testing" mode
**Solution:** This is **normal** for development!
- Click "Advanced" → "Go to [app name] (unsafe)"
- Only affects external test users
- For production, submit for verification (takes 1-2 weeks)

---

## CLI Reference

### Project Management

```bash
# List all your projects
gcloud projects list

# Switch project
gcloud config set project PROJECT_ID

# Delete project (if needed)
gcloud projects delete PROJECT_ID
```

### API Management

```bash
# List enabled APIs
gcloud services list --enabled

# Enable an API
gcloud services enable APINAME.googleapis.com

# Disable an API
gcloud services disable APINAME.googleapis.com

# Check quota
gcloud services quota describe classroom.googleapis.com
```

### OAuth Management

```bash
# List OAuth clients (requires REST API)
PROJECT_ID=$(gcloud config get-value project)
ACCESS_TOKEN=$(gcloud auth application-default print-access-token)

curl -H "Authorization: Bearer $ACCESS_TOKEN" \
  "https://oauth2.googleapis.com/v1/projects/$PROJECT_ID/oauthClients"
```

### Billing

```bash
# List billing accounts
gcloud billing accounts list

# Link billing to project
gcloud billing projects link PROJECT_ID --billing-account=ACCOUNT_ID

# Check project billing status
gcloud billing projects describe PROJECT_ID
```

---

## What You Can Do From CLI (Summary)

✅ **Fully Automated:**
- Authenticate with Google
- Create GCP project
- Enable APIs
- Link billing account
- Configure environment variables

⚠️ **Requires Web Console (2-5 minutes):**
- Create OAuth client (2 min)
- Configure OAuth consent screen (3 min)

**Why web console required:**
Google doesn't provide CLI for these security-sensitive operations. But the script:
- Opens the exact pages for you
- Provides step-by-step instructions
- Makes it as painless as possible

---

## Cost Breakdown

| Item | Cost |
|------|------|
| GCP project | $0 |
| Google Classroom API | $0 (free forever) |
| Google People API | $0 (free forever) |
| Billing account requirement | $0 (no charges) |
| **Total** | **$0** |

**Note:** You need to add a payment method for billing account, but Google Classroom API is completely free with no usage limits.

---

## Next Steps After Setup

1. ✅ Run the setup script: `./scripts/setup-google-classroom.sh`
2. ✅ Add Google provider to NextAuth
3. ✅ Test "Sign in with Google"
4. 📝 Implement class import feature (Phase 2 of roadmap)
5. 📝 Build teacher dashboard
6. 📝 Add assignment integration

Refer to `.claude/PLATFORM_INTEGRATION_ROADMAP.md` for full implementation timeline.

---

## Security Best Practices

### Protect Your Secrets

```bash
# Check .env.local is in .gitignore
cat .gitignore | grep .env.local
```

Should see:
```
.env*.local
```

### Rotate Credentials Periodically

```bash
# Open credentials page
PROJECT_ID=$(gcloud config get-value project)
open "https://console.cloud.google.com/apis/credentials?project=$PROJECT_ID"

# Delete old client, create new one
# Update .env.local with new credentials
```

### Use Different Credentials for Dev/Prod

**Development:**
- OAuth client: `http://localhost:3000/api/auth/callback/google`
- Test users only

**Production:**
- OAuth client: `https://abaci.one/api/auth/callback/google`
- Verified app (submit for review)

---

## Resources

**Official Documentation:**
- GCP CLI: https://cloud.google.com/sdk/gcloud
- Classroom API: https://developers.google.com/classroom
- OAuth 2.0: https://developers.google.com/identity/protocols/oauth2

**Script Location:**
- `scripts/setup-google-classroom.sh`

**Configuration Files:**
- `.env.local` (credentials)
- `src/app/api/auth/[...nextauth]/route.ts` (NextAuth config)

---

**Ready to run?**

```bash
./scripts/setup-google-classroom.sh
```

Good luck! 🚀
