from __future__ import annotations

from dataclasses import dataclass
from typing import Final

from fastapi import Request, Response

from app.core.config import settings


COOKIE_PATH: Final[str] = "/"


@dataclass(frozen=True)
class AuthCookie:
    name: str

    def apply(self, response: Response, token: str) -> None:
        response.set_cookie(
            key=self.name,
            value=token,
            httponly=True,
            secure=settings.session_cookie_secure,
            samesite=settings.session_cookie_samesite,
            domain=settings.session_cookie_domain,
            path=COOKIE_PATH,
            max_age=settings.session_ttl_seconds,
        )

    def clear(self, response: Response) -> None:
        response.delete_cookie(
            key=self.name,
            domain=settings.session_cookie_domain,
            path=COOKIE_PATH,
        )


CLIENT_AUTH_COOKIE = AuthCookie(settings.session_cookie_name)
ADMIN_AUTH_COOKIE = AuthCookie(settings.admin_session_cookie_name)


def get_bearer_or_cookie_token(request: Request, *, cookie_name: str) -> str | None:
    authorization = request.headers.get("authorization", "").strip()
    if authorization.lower().startswith("bearer "):
        token = authorization[7:].strip()
        if token:
            return token
    cookie_value = request.cookies.get(cookie_name)
    if cookie_value:
        return cookie_value
    return None
