from __future__ import annotations

import structlog
from aiogram import F, Router
from aiogram.types import Message

from adapter.telegram import db

logger = structlog.get_logger(__name__)

router = Router(name="topic_events")


@router.message(F.forum_topic_created)
async def on_topic_created(message: Message) -> None:
    """User created a topic via Telegram UI — register it as a new chat.

    Skip topics created by the bot itself — those are already registered
    by cmd_new at the time create_forum_topic() is called.
    """
    if message.from_user is None or message.from_user.id == message.bot.id:
        return
    user_id = message.from_user.id
    thread_id = message.message_thread_id
    name = message.forum_topic_created.name
    db.create_chat(user_id=user_id, thread_id=thread_id, chat_name=name)
    logger.info("topic_created", user_id=user_id, thread_id=thread_id, name=name)


@router.message(F.forum_topic_edited)
async def on_topic_edited(message: Message) -> None:
    """User renamed a topic via Telegram UI — sync chat_name in DB."""
    user_id = message.from_user.id
    thread_id = message.message_thread_id
    new_name = message.forum_topic_edited.name
    if db.get_chat(user_id=user_id, thread_id=thread_id) is None:
        return
    db.rename_chat(user_id=user_id, thread_id=thread_id, new_name=new_name)
    logger.info("topic_renamed", user_id=user_id, thread_id=thread_id, new_name=new_name)


@router.message(F.forum_topic_closed)
async def on_topic_closed(message: Message) -> None:
    """User closed a topic via Telegram UI — auto-archive the chat."""
    user_id = message.from_user.id
    thread_id = message.message_thread_id
    if db.get_chat(user_id=user_id, thread_id=thread_id) is None:
        return
    db.archive_chat(user_id=user_id, thread_id=thread_id)
    logger.info("topic_closed_archived", user_id=user_id, thread_id=thread_id)
