"""Account page data service — provides serialized dicts for .sx defpages."""
from __future__ import annotations


class AccountPageService:
    """Service for account page data, callable via (service "account-page" ...)."""

    async def newsletters_data(self, session, **kw):
        """Return newsletter list with user subscription status."""
        from quart import g
        from sqlalchemy import select
        from shared.models import UserNewsletter
        from shared.models.ghost_membership_entities import GhostNewsletter

        result = await session.execute(
            select(GhostNewsletter).order_by(GhostNewsletter.name)
        )
        all_newsletters = result.scalars().all()

        sub_result = await session.execute(
            select(UserNewsletter).where(
                UserNewsletter.user_id == g.user.id,
            )
        )
        user_subs = {un.newsletter_id: un for un in sub_result.scalars().all()}

        newsletter_list = []
        for nl in all_newsletters:
            un = user_subs.get(nl.id)
            newsletter_list.append({
                "newsletter": {"id": nl.id, "name": nl.name, "description": nl.description},
                "un": {"newsletter_id": un.newsletter_id, "subscribed": un.subscribed} if un else None,
                "subscribed": un.subscribed if un else False,
            })

        from shared.infrastructure.urls import account_url
        return {
            "newsletter_list": newsletter_list,
            "account_url": account_url(""),
        }
