from fastapi import Header, Request, Response
from pydantic import BaseModel

from config import api_config


class CommonHeaders(BaseModel):
    language: str | None = None
    domain: str | None = None
    timezone: str | None = None
    token: str | None = None
    request: Request | None = None
    response: Response | None = None
    operation_id: str | None = None
    
    model_config = {
        "arbitrary_types_allowed": True
    }

    @classmethod
    def as_dependency(
        cls,
        request: Request,
        response: Response,
        language: str = Header(None, alias="language"),
        domain: str = Header(None, alias="domain"),
        tz: str = Header(None, alias="timezone"),
    ):
        token = request.headers.get(api_config.ACCESS_TOKEN_TAG, None)

        # Extract operation_id from the route
        operation_id = None
        if hasattr(request.scope.get("route"), "operation_id"):
            operation_id = request.scope.get("route").operation_id

        return cls(
            language=language,
            domain=domain,
            timezone=tz,
            token=token,
            request=request,
            response=response,
            operation_id=operation_id,
        )

    def get_headers_dict(self):
        """Convert the headers to a dictionary format used in the application"""
        import uuid

        return {
            "language": self.language or "",
            "domain": self.domain or "",
            "eys-ext": f"{str(uuid.uuid4())}",
            "tz": self.timezone or "GMT+3",
            "token": self.token,
        }
