"""Unified notification helper — in-app + Telegram groups + FCM push."""
import asyncio
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.notification import Notification
from app.models.user import User
from app.models.app_setting import AppSetting


async def notify(db: AsyncSession, user: User, title: str, body: str, link: str = "") -> None:
    """
    Create an in-app notification for `user` + fire FCM push in the background.
    Telegram is sent via group channels (notify_user_group / notify_admin_group).
    Caller is responsible for db.commit().
    """
    db.add(Notification(user_id=user.id, title=title, body=body, link=link))

    if user.push_token:
        asyncio.create_task(_send_fcm(user.push_token, title, body, link))


async def notify_user_by_id(db: AsyncSession, user_id: int, title: str,
                             body: str, link: str = "") -> None:
    """Fetch user by ID and create in-app notification (+ FCM push)."""
    user = await db.get(User, user_id)
    if user and user.is_active:
        await notify(db, user, title, body, link)


async def notify_admins(db: AsyncSession, title: str, body: str, link: str = "") -> None:
    """Create in-app notification for all active admins (+ FCM push per admin)."""
    result = await db.execute(
        select(User).where(User.role == "admin", User.is_active == True)  # noqa: E712
    )
    for admin in result.scalars().all():
        await notify(db, admin, title, body, link)


async def notify_user_group(db: AsyncSession, title: str, body: str, link: str = "", thread_key: str | None = None) -> None:
    """Send Telegram message to the user group channel, optionally to a specific topic thread."""
    setting = await db.get(AppSetting, "telegram_user_group_id")
    if not setting or not setting.value:
        return
    thread_id: int | None = None
    if thread_key:
        thread_setting = await db.get(AppSetting, thread_key)
        if thread_setting and thread_setting.value:
            try:
                thread_id = int(thread_setting.value)
            except ValueError:
                pass
    asyncio.create_task(_send_telegram(setting.value, title, body, link, thread_id))


async def notify_admin_group(db: AsyncSession, title: str, body: str, link: str = "") -> None:
    """Send Telegram message to the admin group channel."""
    setting = await db.get(AppSetting, "telegram_admin_group_id")
    if setting and setting.value:
        asyncio.create_task(_send_telegram(setting.value, title, body, link))


# ── Background senders ─────────────────────────────────────────────────────────

async def _send_telegram(chat_id: str, title: str, body: str, link: str, message_thread_id: int | None = None) -> None:
    try:
        from app.services.telegram import send_telegram
        msg = f"*[Jarvis] {title}*\n{body}"
        if link:
            msg += f"\nhttps://jarvis.goteku.com{link}"
        await send_telegram(chat_id, msg, message_thread_id)
    except Exception as e:
        print(f"[notifier] Telegram error: {e}")


async def _send_fcm(token: str, title: str, body: str, link: str) -> None:
    try:
        from app.services.push_notification import send_push
        await send_push(token, title, body, {"link": link})
    except Exception as e:
        print(f"[notifier] FCM error: {e}")
