"""
Deadline API - Proxy zu Go Consent Service für Consent-Deadlines und Account-Sperrung
"""

from fastapi import APIRouter, HTTPException, Header
from typing import Optional
import httpx

router = APIRouter(prefix="/v1", tags=["Deadlines"])

CONSENT_SERVICE_URL = "http://localhost:8081"


async def proxy_request(
    method: str,
    path: str,
    authorization: Optional[str] = None,
    json_data: dict = None
):
    """Proxy request to Go consent service."""
    headers = {}
    if authorization:
        headers["Authorization"] = authorization

    async with httpx.AsyncClient() as client:
        try:
            response = await client.request(
                method,
                f"{CONSENT_SERVICE_URL}{path}",
                headers=headers,
                json=json_data,
                timeout=30.0
            )

            if response.status_code >= 400:
                raise HTTPException(
                    status_code=response.status_code,
                    detail=response.json().get("error", "Request failed")
                )

            return response.json()
        except httpx.RequestError as e:
            raise HTTPException(status_code=503, detail=f"Consent service unavailable: {str(e)}")


@router.get("/consent/deadlines")
async def get_pending_deadlines(
    authorization: Optional[str] = Header(None)
):
    """Holt alle ausstehenden Consent-Deadlines des Benutzers."""
    return await proxy_request(
        "GET",
        "/api/v1/consent/deadlines",
        authorization=authorization
    )


@router.get("/account/suspension-status")
async def get_suspension_status(
    authorization: Optional[str] = Header(None)
):
    """Gibt den Sperrstatus des Accounts zurück."""
    return await proxy_request(
        "GET",
        "/api/v1/account/suspension-status",
        authorization=authorization
    )


@router.post("/admin/deadlines/process")
async def process_deadlines(
    authorization: Optional[str] = Header(None)
):
    """Löst die Deadline-Verarbeitung manuell aus (nur Admin)."""
    return await proxy_request(
        "POST",
        "/api/v1/admin/deadlines/process",
        authorization=authorization
    )
