from starlette.requests import Request

from data.schemas.administration.api_key import ApiKey
from data.schemas.administration.api_key_dao import apiKeyDao


class RouteApiKeyExtension:

    @classmethod
    async def get_api_key(cls, request: Request) -> ApiKey:
        auth_header = request.headers.get("Authorization", None)
        api_key = auth_header.split(" ")[1]
        return await apiKeyDao.find_single_by(
            [{ApiKey.key: api_key}, {ApiKey.deleted: False}]
        )

    @classmethod
    async def _verify_api_key(cls, req: Request) -> bool:
        auth_header = req.headers.get("Authorization", None)
        if not auth_header or not auth_header.startswith("API-Key "):
            return False

        api_key = auth_header.split(" ")[1]
        api_key_from_db = await apiKeyDao.find_single_by(
            [{ApiKey.key: api_key}, {ApiKey.deleted: False}]
        )
        return api_key_from_db is not None and not api_key_from_db.deleted
