"""
Роуты страницы синхронизации с Intradesk.

GET  /admin/sync          — страница с кнопками и историей
POST /admin/sync/run      — запустить синхронизацию (sync_type в форме)
"""
from __future__ import annotations

from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import RedirectResponse

from admin.auth import require_admin
from admin.templates_env import templates
from database.connection import get_db
from database.queries.intradesk import get_last_sync, get_recent_sync_logs
from external.intradesk_sync import run_sync

router = APIRouter()

_SYNC_LABELS = {
    "clients": "Клиенты / организации",
    "users":   "Пользователи (контактные лица)",
    "tasks":   "Заявки",
    "all":     "Всё сразу",
}


@router.get("/sync", dependencies=[Depends(require_admin)])
async def sync_page(request: Request):
    db = get_db()
    logs = await get_recent_sync_logs(db, limit=20)

    last: dict[str, dict | None] = {}
    for k in ("clients", "users", "tasks"):
        last[k] = await get_last_sync(db, k)

    return templates.TemplateResponse(
        "sync/index.html",
        {
            "request": request,
            "logs": logs,
            "last": last,
            "sync_labels": _SYNC_LABELS,
        },
    )


@router.post("/sync/run", dependencies=[Depends(require_admin)])
async def sync_run(sync_type: str = Form(...)):
    if sync_type not in _SYNC_LABELS:
        return RedirectResponse("/admin/sync", status_code=303)
    await run_sync(sync_type)
    return RedirectResponse("/admin/sync", status_code=303)
