@router.get("/accounts")
async def list_accounts(user: User = Depends(get_current_user),
                        db: AsyncSession = Depends(get_db)):
    rows = (await db.execute(select(GmailAccount).where(
        GmailAccount.user_id == user.id).order_by(GmailAccount.id))).scalars().all()
    return {"accounts": [_account_out(a) for a in rows], "count": len(rows)}


@router.post("/accounts/connect")
async def connect_start(user: User = Depends(get_current_user_csrf),
                        db: AsyncSession = Depends(get_db)):
    """Return the Google authorization URL for this user to open (real OAuth start).
    Uses the user's most recently imported client config when available."""
    from sqlalchemy import select as _select

    cfg_row = (await db.execute(
        _select(OAuthClientConfig)
        .where(OAuthClientConfig.user_id == user.id, OAuthClientConfig.is_active == True)  # noqa
        .order_by(OAuthClientConfig.id.desc()))).scalars().first()
    if cfg_row is not None:
        client = gmail_service.resolve_client_config(cfg_row)
    else:
        try:
            client = gmail_service.resolve_client_config()
        except gmail_service.GmailOauthError:
            raise HTTPException(400, "No Google OAuth client configuration imported yet. "
                                     "Use 'Import Gmail Configuration' first.")
    from app.api.routers.auth import google_start_impl
    return await google_start_impl(user, client)


