from arclet.entari import plugin, Session, MessageCreatedEvent, SendResponse

from entari_plugin_database import AsyncSession  # entari: plugin

from .config import config
from .model import MessageRecord


@plugin.listen(MessageCreatedEvent)
async def message_receive(
    session: Session,
    event: MessageCreatedEvent,
    db_session: AsyncSession,
    is_notice_me: bool = False,
    is_reply_me: bool = False,
) -> None:
    if config.to_me_only and not (is_notice_me or is_reply_me):
        return

    record = MessageRecord(
        user_id=event.user.id,
        channel_id=event.channel.id,
        platform=event.account.platform,
        time=session.event.timestamp,
        type="message",
        message_id=event.message.id,
        message=event.message.dump(),
        plain_text=event.content.extract_plain_text(),
    )

    db_session.add(record)
    await db_session.commit()


async def message_send(
    session: Session,
    event: SendResponse,
    db_session: AsyncSession,
) -> None:
    if event.session is None or event.session.event.message is None:
        return

    record = MessageRecord(
        user_id=event.account.self_id,
        channel_id=event.channel,
        platform=event.account.platform,
        time=session.event.timestamp,
        type="message_sent",
        message_id=event.session.event.message.id,
        message=event.result[0].dump(),
        plain_text=event.message.extract_plain_text(),
    )

    db_session.add(record)
    await db_session.commit()


if config.record_send:
    plugin.listen(SendResponse)(message_send)
