import json
from database.connection import get_db


async def log_message(
    direction: str,
    max_user_id: int | None,
    max_chat_id: int | None,
    message_id: str | None,
    text: str | None,
    attachments: list | None = None,
) -> None:
    db = get_db()
    att_json = json.dumps(attachments, ensure_ascii=False) if attachments else None
    await db.execute(
        """
        INSERT INTO message_log
            (direction, max_user_id, max_chat_id, message_id, text, attachment_json)
        VALUES (?, ?, ?, ?, ?, ?)
        """,
        (direction, max_user_id, max_chat_id, message_id, text, att_json),
    )
    await db.commit()


async def get_message_log(
    max_user_id: int | None = None,
    max_chat_id: int | None = None,
    limit: int = 100,
    offset: int = 0,
) -> list[dict]:
    db = get_db()
    conditions = []
    params: list = []
    if max_user_id is not None:
        conditions.append("max_user_id = ?")
        params.append(max_user_id)
    if max_chat_id is not None:
        conditions.append("max_chat_id = ?")
        params.append(max_chat_id)
    where = ("WHERE " + " AND ".join(conditions)) if conditions else ""
    params += [limit, offset]
    query = f"""
        SELECT * FROM message_log
        {where}
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
    """
    async with db.execute(query, params) as cur:
        rows = await cur.fetchall()
    return [dict(r) for r in rows]


async def get_chat_list() -> list[dict]:
    """Последнее сообщение на каждый чат для списка чатов в панели."""
    db = get_db()
    async with db.execute(
        """
        SELECT ml.max_chat_id, ml.max_user_id, ml.text, ml.created_at,
               bu.first_name, bu.username
        FROM message_log ml
        LEFT JOIN bot_users bu ON bu.max_user_id = ml.max_user_id
        WHERE ml.max_chat_id IS NOT NULL
        GROUP BY ml.max_chat_id
        HAVING ml.id = MAX(ml.id)
        ORDER BY ml.created_at DESC
        """
    ) as cur:
        rows = await cur.fetchall()
    return [dict(r) for r in rows]
