import logging

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from app.core.database import execute_query
from app.modules.telefoni.backend.utils import normalize_external_number

logger = logging.getLogger(__name__)
router = APIRouter()
templates = Jinja2Templates(directory="app")


@router.get("/telefoni", response_class=HTMLResponse)
async def telefoni_log_page(request: Request):
    initial_calls = []
    try:
        initial_calls = execute_query(
            """
            SELECT
                t.id,
                t.direction,
                COALESCE(
                    NULLIF(TRIM(t.ekstern_nummer), '')
                ) AS display_number,
                t.started_at,
                t.duration_sec,
                t.ended_at,
                u.full_name,
                u.username,
                t.kontakt_id,
                CONCAT(COALESCE(c.first_name, ''), ' ', COALESCE(c.last_name, '')) AS contact_name,
                t.sag_id,
                s.titel AS sag_titel
            FROM telefoni_opkald t
            LEFT JOIN users u ON u.user_id = t.bruger_id
            LEFT JOIN contacts c ON c.id = t.kontakt_id
            LEFT JOIN sag_sager s ON s.id = t.sag_id
            ORDER BY t.started_at DESC
            LIMIT 50
            """,
            (),
        ) or []
        for row in initial_calls:
            display_raw = row.get("display_number")
            repaired = normalize_external_number(display_raw)
            if repaired:
                row["display_number"] = repaired
    except Exception as e:
        logger.warning("⚠️ Could not load initial telefoni calls for SSR fallback: %s", e)

    return templates.TemplateResponse(
        "modules/telefoni/templates/log.html",
        {
            "request": request,
            "initial_calls": initial_calls,
        },
    )
