from datetime import datetime
from typing import Literal
from collections.abc import Iterable, Sequence

from entari_plugin_database import get_session
from sqlalchemy import select

from .model import MessageRecord


async def get_message_records(
    user_ids: list[str] | None = None,
    channel_ids: list[str] | None = None,
    platforms: Iterable[str] | None = None,
    time_start: datetime | None = None,
    time_end: datetime | None = None,
    types: Iterable[Literal["message", "message_sent"]] | None = None,
) -> Sequence[MessageRecord]:
    async with get_session() as db_session:
        query = select(MessageRecord)

        if user_ids:
            query = query.where(MessageRecord.user_id.in_(user_ids))

        if channel_ids:
            query = query.where(MessageRecord.channel_id.in_(channel_ids))

        if platforms:
            query = query.where(MessageRecord.platform.in_(list(platforms)))

        if time_start:
            query = query.where(MessageRecord.time >= time_start)

        if time_end:
            query = query.where(MessageRecord.time <= time_end)

        if types:
            query = query.where(MessageRecord.type.in_(list(types)))

        result = await db_session.execute(query)
        records = result.scalars().all()

        return records
