"""
Admin Auth Routes

FastAPI endpoints for admin token management.
"""

import logging
import secrets
from datetime import datetime, timedelta, timezone

from fastapi import APIRouter

from backend.web.core.auth import AdminTokenDep, TokenRepoDep
from backend.web.schemas.admin import (
    AdminTokenCreate,
    AdminTokenResponse,
)
from backend.web.schemas.common import ErrorResponse

logger = logging.getLogger(__name__)


def create_auth_router() -> APIRouter:
    """Create admin auth router."""
    router = APIRouter(prefix="/admin/auth", tags=["Admin Auth"])

    @router.post(
        "/token",
        response_model=AdminTokenResponse,
        responses={
            400: {"model": ErrorResponse, "description": "Invalid request"},
        },
        summary="Create admin token",
        description="Create a new admin authentication token.",
    )
    async def create_token(
        request: AdminTokenCreate,
        tokens: TokenRepoDep,
    ) -> AdminTokenResponse:
        """Create a new admin token."""
        # Generate secure token
        token = secrets.token_urlsafe(32)

        # Calculate expiration (use timezone-aware datetime)
        expires_at = None
        if request.expires_in_days:
            expires_at = datetime.now(timezone.utc) + timedelta(days=request.expires_in_days)

        # Create token in database
        tokens.create(
            token=token,
            name=request.name,
            expires_at=expires_at,
        )

        return AdminTokenResponse(
            token=token,
            name=request.name,
            expires_at=expires_at,
            message="Admin token created successfully",
        )

    @router.delete(
        "/token",
        responses={
            401: {"model": ErrorResponse, "description": "Invalid token"},
        },
        summary="Revoke admin token",
        description="Revoke the current admin token.",
    )
    async def revoke_token(
        admin_token: AdminTokenDep,
        tokens: TokenRepoDep,
    ) -> dict:
        """Revoke the current admin token."""
        tokens.deactivate(admin_token)
        return {
            "status": "revoked",
            "message": "Admin token has been revoked",
        }

    return router
