"""Запросы к таблице task_watch — слежение за задачами для push-уведомлений."""
from database.connection import get_db


async def get_watched_clients() -> list[dict]:
    """Все организации с привязанным intradesk_id."""
    db = get_db()
    async with db.execute(
        "SELECT id AS org_id, intradesk_id FROM organizations WHERE intradesk_id IS NOT NULL"
    ) as cur:
        rows = await cur.fetchall()
    return [dict(r) for r in rows]


async def get_task_watch(task_id: int) -> dict | None:
    """Получить состояние слежения для одной задачи."""
    db = get_db()
    async with db.execute(
        "SELECT * FROM task_watch WHERE task_id = ?", (task_id,)
    ) as cur:
        row = await cur.fetchone()
    return dict(row) if row else None


async def upsert_task_watch(
    task_id: int,
    client_id: int,
    task_number: int | None,
    last_updatedat: str,
    last_comment_date: str,
) -> None:
    """Создать или обновить запись слежения."""
    db = get_db()
    await db.execute(
        """
        INSERT INTO task_watch (task_id, client_id, task_number, last_updatedat, last_comment_date)
        VALUES (?, ?, ?, ?, ?)
        ON CONFLICT(task_id) DO UPDATE SET
            last_updatedat    = excluded.last_updatedat,
            last_comment_date = excluded.last_comment_date,
            task_number       = COALESCE(excluded.task_number, task_number)
        """,
        (task_id, client_id, task_number, last_updatedat, last_comment_date),
    )
    await db.commit()


async def remove_tasks_not_in(client_id: int, task_ids: set[int]) -> None:
    """Удалить закрытые/архивные задачи клиента из слежения."""
    db = get_db()
    if task_ids:
        placeholders = ",".join("?" * len(task_ids))
        await db.execute(
            f"DELETE FROM task_watch WHERE client_id = ? AND task_id NOT IN ({placeholders})",
            (client_id, *task_ids),
        )
    else:
        # Все задачи закрыты — убираем всё по клиенту
        await db.execute("DELETE FROM task_watch WHERE client_id = ?", (client_id,))
    await db.commit()
