from __future__ import annotations

import sqlite3
from typing import Any


class MentorRepository:
    @staticmethod
    def preferences(connection: sqlite3.Connection, user_id: int) -> dict[str, dict[str, Any]]:
        return {
            str(row["mentor_id"]): dict(row)
            for row in connection.execute(
                "SELECT * FROM mentor_preferences WHERE user_id = ?", (user_id,)
            )
        }

    @staticmethod
    def save_preferences(
        connection: sqlite3.Connection,
        user_id: int,
        order: list[str],
        pinned: set[str],
        updated_at: str,
    ) -> None:
        connection.execute("DELETE FROM mentor_preferences WHERE user_id = ?", (user_id,))
        connection.executemany(
            """
            INSERT INTO mentor_preferences (
                user_id, mentor_id, pinned, sort_order, updated_at
            ) VALUES (?, ?, ?, ?, ?)
            """,
            (
                (user_id, mentor_id, int(mentor_id in pinned), index, updated_at)
                for index, mentor_id in enumerate(order)
            ),
        )

    @staticmethod
    def messages(
        connection: sqlite3.Connection,
        user_id: int,
        mentor_id: str,
        trade_date: str,
        limit: int = 200,
    ) -> tuple[sqlite3.Row, ...]:
        rows = connection.execute(
            """
            SELECT * FROM mentor_messages
            WHERE user_id = ? AND mentor_id = ? AND trade_date = ?
            ORDER BY id DESC LIMIT ?
            """,
            (user_id, mentor_id, trade_date, limit),
        ).fetchall()
        return tuple(reversed(rows))

    @staticmethod
    def add_message(
        connection: sqlite3.Connection,
        *,
        user_id: int,
        mentor_id: str,
        trade_date: str,
        role: str,
        content: str,
        request_id: str | None,
        status: str,
        created_at: str,
    ) -> int:
        cursor = connection.execute(
            """
            INSERT INTO mentor_messages (
                user_id, mentor_id, trade_date, role, content,
                request_id, status, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                user_id,
                mentor_id,
                trade_date,
                role,
                content,
                request_id,
                status,
                created_at,
            ),
        )
        return int(cursor.lastrowid)

    @staticmethod
    def clear_messages(
        connection: sqlite3.Connection, user_id: int, mentor_id: str, trade_date: str
    ) -> int:
        cursor = connection.execute(
            """
            DELETE FROM mentor_messages
            WHERE user_id = ? AND mentor_id = ? AND trade_date = ?
            """,
            (user_id, mentor_id, trade_date),
        )
        return cursor.rowcount
