"""Service methods for account data queries.

Extracted from account/bp/data/routes.py to enable sx defquery conversion.
"""
from __future__ import annotations

from typing import Any

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from shared.models import User


class SqlAccountDataService:

    async def user_by_email(
        self, session: AsyncSession, *, email: str,
    ) -> dict[str, Any] | None:
        email = (email or "").strip().lower()
        if not email:
            return None
        result = await session.execute(
            select(User.id).where(User.email.ilike(email))
        )
        row = result.first()
        if not row:
            return None
        return {"user_id": row[0]}

    async def newsletters(self, session: AsyncSession) -> list[dict[str, Any]]:
        from shared.models.ghost_membership_entities import GhostNewsletter
        result = await session.execute(
            select(
                GhostNewsletter.id, GhostNewsletter.ghost_id,
                GhostNewsletter.name, GhostNewsletter.slug,
            ).order_by(GhostNewsletter.name)
        )
        return [
            {"id": row[0], "ghost_id": row[1], "name": row[2], "slug": row[3]}
            for row in result.all()
        ]
