"""Auth service — JWT issuance + verification (passlib[bcrypt] + pyjwt).

Only rendered when ``use_auth == "yes"``.
"""

from __future__ import annotations

from datetime import datetime, timedelta, timezone
from typing import Any

import jwt
from fastapi import HTTPException, status
from passlib.context import CryptContext

from {{ cookiecutter.project_name }}.config.settings import settings
from {{ cookiecutter.project_name }}.db.models.user import User

_pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")


class AuthService:
    """Stateless auth service — JWT + password hashing."""

    @staticmethod
    def hash_password(password: str) -> str:
        return _pwd.hash(password)

    @staticmethod
    def verify_password(plain: str, hashed: str) -> bool:
        return _pwd.verify(plain, hashed)

    @staticmethod
    def create_access_token(username: str) -> str:
        expire = datetime.now(timezone.utc) + timedelta(
            minutes=settings.jwt.expire_minutes,
        )
        payload: dict[str, Any] = {"sub": username, "exp": expire}
        return jwt.encode(payload, settings.jwt.secret, algorithm=settings.jwt.algorithm)

    @staticmethod
    async def register(username: str, email: str, password: str) -> User:
        hashed = AuthService.hash_password(password)
        return await User.create(
            username=username, email=email, hashed_password=hashed,
        )

    @staticmethod
    async def login(username: str, password: str) -> str:
        user = await User.get_or_none(username=username)
        if user is None or not AuthService.verify_password(password, user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid credentials",
            )
        return AuthService.create_access_token(username)

    @staticmethod
    async def decode_access_token(token: str) -> str:
        try:
            payload = jwt.decode(
                token, settings.jwt.secret, algorithms=[settings.jwt.algorithm],
            )
        except jwt.PyJWTError as exc:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token",
            ) from exc
        return str(payload.get("sub", ""))