import datetime
from typing import Annotated

import jwt
from fastapi import Cookie, Depends, HTTPException
from folkugat_web.config import auth as config
from folkugat_web.log import logger


def login(value: str | None) -> bool:
    if value and value.lower() == config.ADMIN_PASSWORD:
        return True
    return False


def logged_in(nota_folkugat: Annotated[str | None, Cookie()] = None) -> bool:
    if not nota_folkugat:
        return False
    try:
        payload = jwt.decode(nota_folkugat, config.JWT_SECRET, algorithms=["HS256"])
    except Exception as exc:
        logger.error("Exception: ", exc)
        return False

    return payload.get('user') == 'admin'


LoggedIn = Annotated[bool, Depends(logged_in)]


def require_login(logged_in: LoggedIn) -> bool:
    if not logged_in:
        raise HTTPException(status_code=403, detail="Must be logged in")
    return True


RequireLogin = Annotated[bool, Depends(require_login)]


def build_payload():
    return {
        'user': 'admin',
        'exp': datetime.datetime.now(tz=datetime.timezone.utc) + config.SESSION_DURATION
    }


def build_token():
    return jwt.encode(build_payload(), config.JWT_SECRET, algorithm="HS256")
