# AUTH SSO FLOW (Frontend)

## 1) New SSO Login Flow
1. Frontend calls `GET /api/v1/auth/microsoft/login`.
2. Redirect user to `data.attributes.url`.
3. Provider redirects to backend callback `GET /api/v1/auth/microsoft/callback?code=...&state=...`.
4. Backend checks existing SSO mapping (`provider=microsoft` + `provider_subject`).
5. Result:
- Mapping + user exists: login success, cookies/session issued.
- Mapping not found: login rejected (`401`).
- Mapping exists but user missing: login rejected (`404`).

## 2) Important Rule
SSO **does not create new account automatically**. User must already exist and be linked first.

## 3) Link SSO (for logged-in existing user)
Endpoint: `POST /api/v1/auth/sso/link`

Auth: required (same auth cookie/session as normal login).

Request:
```json
{
  "data": {
    "type": "auth_sso_link",
    "attributes": {
      "provider": "microsoft",
      "code": "<microsoft_authorization_code>"
    }
  }
}
```

Success `200`:
```json
{
  "data": {
    "type": "auth_sso_link",
    "attributes": {
      "provider": "microsoft",
      "provider_subject": "00000000-0000-0000-0000-000000000000",
      "email": "user@example.com"
    }
  }
}
```

## 4) Unlink SSO
Endpoint: `DELETE /api/v1/auth/sso/unlink`

Auth: required.

Request:
```json
{
  "data": {
    "type": "auth_sso_unlink",
    "attributes": {
      "provider": "microsoft"
    }
  }
}
```

Success `200`:
```json
{
  "data": {
    "type": "auth_sso_unlink",
    "attributes": {
      "provider": "microsoft",
      "unlinked": true
    }
  }
}
```

## 5) Endpoint Summary
- `GET /api/v1/auth/microsoft/login`
- `GET /api/v1/auth/microsoft/callback`
- `POST /api/v1/auth/sso/link`
- `DELETE /api/v1/auth/sso/unlink`

## 6) Error Handling (Frontend)
Handle these API errors explicitly:
- `401 Unauthorized`
- `403 Forbidden`
- `404 user not found`
- `401 sso not linked`
- `409 sso already linked`
- `409 sso linked to another user`

Recommended behavior:
- `401 sso not linked`: show message to login manually first, then link SSO in account settings.
- `409` errors on link: inform user mapping conflict and stop retry loop.
- `404 user not found`: force logout and ask user to re-authenticate.
