"""
Роуты просмотра синхронизированных данных из Intradesk.

GET /admin/intradesk/clients                      — список клиентов
GET /admin/intradesk/clients/{client_id}/tasks    — заявки клиента
"""
from __future__ import annotations

from fastapi import APIRouter, Depends, Request

from admin.auth import require_admin
from admin.templates_env import templates
from database.connection import get_db
from database.queries.intradesk import (
    count_tasks_for_client,
    get_all_clients,
    get_client,
    get_distinct_statuses,
    get_tasks_for_client,
    get_users_for_client,
)

router = APIRouter()

_PAGE_SIZE = 30


@router.get("/intradesk/clients", dependencies=[Depends(require_admin)])
async def clients_list(request: Request, search: str = ""):
    db = get_db()
    clients = await get_all_clients(db, search=search)
    return templates.TemplateResponse(
        "intradesk/clients.html",
        {"request": request, "clients": clients, "search": search},
    )


@router.get(
    "/intradesk/clients/{client_id}/tasks",
    dependencies=[Depends(require_admin)],
)
async def client_tasks(
    request: Request,
    client_id: int,
    status: str = "",
    page: int = 0,
):
    db = get_db()
    client = await get_client(db, client_id)
    if client is None:
        return templates.TemplateResponse(
            "intradesk/clients.html",
            {
                "request": request,
                "clients": [],
                "search": "",
                "error": f"Клиент {client_id} не найден",
            },
        )

    tasks = await get_tasks_for_client(
        db, client_id, status_filter=status, page=page, page_size=_PAGE_SIZE
    )
    total = await count_tasks_for_client(db, client_id, status_filter=status)
    statuses = await get_distinct_statuses(db)
    users = await get_users_for_client(db, client_id)

    pages = max(1, (total + _PAGE_SIZE - 1) // _PAGE_SIZE)

    return templates.TemplateResponse(
        "intradesk/client_tasks.html",
        {
            "request": request,
            "client": client,
            "tasks": tasks,
            "users": users,
            "total": total,
            "page": page,
            "pages": pages,
            "page_size": _PAGE_SIZE,
            "status": status,
            "statuses": statuses,
        },
    )
