# Supabase Scripts

## Setup: one account per team

Each team has **one** Supabase Auth account (one email, one password). The 4–5 members of that team all use the same account to log in. They can be connected at the same time and share the same canvases; there is no separate account per person for team users.

---

## Auto-create team and profile (trigger)

After running migration `003_auto_create_team_and_profile.sql`, every new user created in Supabase Auth (dashboard or API) automatically gets:

- A **team** (new team for team users, or shared "Administrateurs" for admins)
- A **profile** linking the user to that team

### Creating users in Supabase Auth dashboard

When you add a user (Authentication → Users → Add user), set **User Metadata** so the trigger can create the right team and profile:

**Team account (shared email):**
```json
{
  "team_name": "Équipe Alpha",
  "is_admin": false
}
```

**Admin account:**
```json
{
  "team_name": "Jean Dupont",
  "is_admin": true
}
```

- `team_name`: Display name for the team (or the admin’s name). If omitted, the email local part is used (e.g. `equipe-alpha@...` → "equipe-alpha").
- `is_admin`: `true` for admins (they are linked to the shared "Administrateurs" team). Omit or `false` for team accounts.

You only need to create the user in Auth; the trigger creates the team and profile.

---

## Backfill existing users (one-time)

If you created users **before** adding the trigger, run the backfill once in the Supabase SQL Editor:

1. Open **SQL Editor** in the Supabase dashboard.
2. Open `supabase/scripts/backfill_profiles_from_auth_users.sql`.
3. Paste and run it.

It creates a team and profile for every auth user that doesn’t have a profile yet, using:

- **User Metadata** (if you set `team_name` / `is_admin` when creating the user)
- Otherwise: team name = email local part, `is_admin` = false

To give existing users proper team names or admin flag, update their metadata first, then run the backfill:

```sql
-- Example: set metadata for an existing user (run in SQL Editor)
UPDATE auth.users
SET raw_user_meta_data = raw_user_meta_data || '{"team_name": "Équipe Alpha", "is_admin": false}'::jsonb
WHERE email = 'equipe-alpha@yourdomain.com';
```

Then run the backfill script.
