# Organization Migration - Quick Start Guide

Quick reference for running the organization migration.

## TL;DR

```bash
# 1. Dry run first (required!)
npm run migrate:organizations:dry

# 2. Review output, then run actual migration
npm run migrate:organizations

# 3. Verify success
npm run verify:organizations
```

## Available Commands

| Command | What it does |
|---------|--------------|
| `npm run migrate:organizations:dry` | Preview what will be migrated (safe, no changes) |
| `npm run migrate:organizations` | Actually migrate users to organizations |
| `npm run verify:organizations` | Verify migration was successful |

## Step-by-Step

### 1. Dry Run (REQUIRED FIRST)

```bash
npm run migrate:organizations:dry
```

**What this does:**
- Shows you which users will be migrated
- Previews organization names and seat limits
- Makes ZERO changes to your database
- Safe to run multiple times

**Expected output:**
```
======================================================================
🚀 Organization Migration (DRY RUN)
======================================================================

📊 Found 3 eligible user(s) for migration

⚠️  DRY RUN MODE - No changes will be made

[1/3] Processing: john@clinic.com (tier3)...
  [DRY RUN] Would create organization for john@clinic.com
  ✅ Would create organization

[2/3] Processing: sara@hospital.com (tier5)...
  [DRY RUN] Would create organization for sara@hospital.com
  ✅ Would create organization
...

======================================================================
📊 MIGRATION SUMMARY
======================================================================

Total users processed: 3
✅ Organizations to be created: 3
⏭️  Skipped (already exist): 0
❌ Failed: 0

💡 Run without --dry-run to actually perform the migration
```

### 2. Review and Decide

Look at the dry run output and check:

✅ **Number of users**: Does it match what you expect?
✅ **Organization names**: Are they appropriate?
✅ **Seat limits**: Correct for each tier?
✅ **No errors**: All users processed successfully?

If everything looks good, proceed to actual migration.

### 3. Run Migration

```bash
npm run migrate:organizations
```

**⚠️ WARNING**: This makes real database changes!

**What happens:**
- Creates organization for each eligible user
- Adds them as OWNER
- Sets seat limits based on subscription tier
- Syncs to both Prisma and Supabase

**Progress indicators:**
- ✅ = Success (organization created)
- ⏭️ = Skipped (already exists)
- ❌ = Failed (see error message)

### 4. Verify Success

```bash
npm run verify:organizations
```

**What this checks:**
- Organization and member counts
- All organizations have valid owners
- Seat configuration is correct
- Eligible users all have organizations
- Prisma/Supabase data is synced

**Expected output:**
```
======================================================================
🔍 Organization Migration Verification
======================================================================

Running: Organization Counts...
  ✅ Found 3 organizations and 3 members

Running: Owner Integrity...
  ✅ All organizations have valid OWNER members

Running: Seat Configuration...
  ✅ All 3 organizations have correct seat configuration

Running: Eligible Users Coverage...
  ✅ All eligible users have organizations

Running: Supabase Sync...
  ✅ Prisma and Supabase are in sync

======================================================================
📊 Verification Summary
======================================================================

Total Checks: 5
✅ Passed: 5
❌ Failed: 0

🎉 All verification checks passed!
✨ Organization migration is successful and healthy.
```

## What Gets Migrated?

### Eligible Users

Users must meet ALL criteria:
- ✅ Role: CUSTOMER
- ✅ Subscription: active or trialing
- ✅ Tier: tier3, tier4, or tier5

### Created Data

For each user, the script creates:

**Organization:**
- Name: From `companyName` or `"[Name]'s Workspace"`
- Owner: The user
- Stripe Customer ID: Copied from user
- Included Seats: Based on tier (tier3=1, tier4=2, tier5=5)
- Purchased Seats: 0

**Organization Member:**
- User: The owner
- Role: OWNER
- Joined At: Now

## Troubleshooting

### "No eligible users found"

**Cause**: No users match the criteria (CUSTOMER role, active subscription, tier 3-5)

**Fix**:
1. Check if you have test data in your database
2. Verify subscription statuses are 'active' or 'trialing'
3. Confirm tiers are tier3, tier4, or tier5

### "Organization already exists"

**Cause**: User already has an organization (idempotent behavior)

**Fix**: This is normal! Script safely skips already-migrated users.

### "Failed to migrate user"

**Cause**: Database error or constraint violation

**Fix**:
1. Check error message in output
2. Verify user has valid subscription
3. Check database constraints
4. Run verification: `npm run verify:organizations`

### Verification fails

**Cause**: Data inconsistency or sync issues

**Fix**:
1. Re-run migration (it's idempotent)
2. Manually fix reported issues
3. Sync to Supabase: `node scripts/sync-all-prisma-to-supabase.mjs`

## Safety Features

✅ **Dry run mode**: Test before making changes
✅ **Idempotent**: Safe to run multiple times
✅ **Transactions**: Each user migrated atomically
✅ **Continue on error**: One failure doesn't stop entire migration
✅ **Detailed logging**: See exactly what happened

## Rollback

If you need to undo the migration:

```bash
# Connect to database
psql -h localhost -p 5432 -U postgres -d mawidi

# Delete all organizations (cascades to members)
DELETE FROM organization_members;
DELETE FROM organizations;
```

Also delete from Supabase:
```bash
# Connect to Supabase
psql -h localhost -p 54322 -U postgres -d postgres

# Delete
DELETE FROM organization_members;
DELETE FROM organizations;
```

## Next Steps

After successful migration:

1. **Test the feature**: Log in as a migrated user and test team management
2. **Send notifications**: Email users about new multi-staff capability
3. **Monitor**: Watch for any issues in production logs
4. **Document**: Update user-facing docs with team invite instructions

## Support

Need help? Check:
- Full guide: `/scripts/MIGRATION-ORGANIZATIONS.md`
- Type definitions: `/lib/types/organization.types.ts`
- Service layer: `/lib/services/organization.service.ts`
- Database utilities: `/lib/dual-database.ts`
