from fastapi import Response

from bluefox_auth.csrf import generate_csrf_token
from bluefox_auth.settings import AuthSettings


def set_auth_cookies(
    response: Response,
    access_token: str,
    refresh_token: str,
    settings: AuthSettings,
) -> str:
    """Set HttpOnly auth cookies and a CSRF cookie. Returns the CSRF token."""
    # Access token — HttpOnly
    response.set_cookie(
        key=settings.cookie_name_access,
        value=access_token,
        httponly=True,
        secure=settings.cookie_secure,
        samesite=settings.cookie_samesite,
        domain=settings.cookie_domain,
        path=settings.cookie_path,
        max_age=settings.access_token_expire_minutes * 60,
    )
    # Refresh token — HttpOnly, restricted to auth prefix
    response.set_cookie(
        key=settings.cookie_name_refresh,
        value=refresh_token,
        httponly=True,
        secure=settings.cookie_secure,
        samesite=settings.cookie_samesite,
        domain=settings.cookie_domain,
        path=settings.auth_prefix,
        max_age=settings.refresh_token_expire_days * 86400,
    )
    # CSRF token — NOT HttpOnly (JS must read it)
    csrf_token = generate_csrf_token()
    response.set_cookie(
        key=settings.cookie_name_csrf,
        value=csrf_token,
        httponly=False,
        secure=settings.cookie_secure,
        samesite=settings.cookie_samesite,
        domain=settings.cookie_domain,
        path=settings.cookie_path,
        max_age=settings.access_token_expire_minutes * 60,
    )
    return csrf_token


def clear_auth_cookies(response: Response, settings: AuthSettings) -> None:
    """Clear all auth cookies."""
    response.delete_cookie(
        key=settings.cookie_name_access,
        path=settings.cookie_path,
        domain=settings.cookie_domain,
    )
    response.delete_cookie(
        key=settings.cookie_name_refresh,
        path=settings.auth_prefix,
        domain=settings.cookie_domain,
    )
    response.delete_cookie(
        key=settings.cookie_name_csrf,
        path=settings.cookie_path,
        domain=settings.cookie_domain,
    )
