"""Domain admin API proxy for Ligbox Console — Spec 035 / 037 V3."""

from __future__ import annotations

import os

from fastapi import APIRouter, Depends, HTTPException, Query

from app import auth
from app.dns_viewer import fetch_dns_viewer
from app.openpanel_dns import fetch_openpanel_bind_records
from app.permissions import can_read_dns_viewer

router = APIRouter(prefix="/api/v1/domain-console", tags=["domain-console"])

DNS_VIEWER_ENABLED = os.getenv("DNS_VIEWER_ENABLED", "1").lower() in ("1", "true", "yes")

STAFF_ROLES = frozenset(
    {
        "super_admin",
        "ops_lead",
        "devops",
        "seo",
        "technician",
        "developer",
        "noc",
        "sales_admin",
        "sales_support",
    }
)


@router.get("/dns/viewer/{domain}")
async def domain_console_dns_viewer(
    domain: str,
    email_service: bool | None = Query(default=True),
    include_public: bool = Query(default=True),
    user: auth.DeskUser = Depends(auth.get_current_user),
):
    """DNS Viewer for Console /admin/dominio."""
    if not DNS_VIEWER_ENABLED:
        raise HTTPException(404, "DNS Viewer disabled")
    if not can_read_dns_viewer(user.role):
        raise HTTPException(403, "insufficient permissions")
    domain = domain.lower().strip().rstrip(".")
    payload = await fetch_dns_viewer(
        domain,
        role=user.role,
        email_service=email_service,
        include_public=include_public,
    )
    if user.role not in STAFF_ROLES:
        payload["edit_links"] = [
            link
            for link in payload.get("edit_links", [])
            if link.get("provider") not in ("cf_ligbox", "openpanel_admin", "openpanel_bind")
            and link.get("audience") != "staff"
        ]
    return payload


@router.get("/dns/openpanel/records")
async def domain_console_openpanel_records(
    domain: str = Query(..., min_length=3),
    user: auth.DeskUser = Depends(auth.get_current_user),
):
    if not can_read_dns_viewer(user.role):
        raise HTTPException(403, "insufficient permissions")
    return fetch_openpanel_bind_records(domain.lower().strip().rstrip("."))
