from sqlalchemy.ext.asyncio import AsyncSession

from core.security import verify_password
from core.jwt import create_access_token, create_refresh_token

from domains.users.repo import get_user_by_username


async def authenticate_user(
    db: AsyncSession,
    username: str,
    secret: str
):

    user = await get_user_by_username(db, username)

    if not user:
        return None

    if not user.is_active:
        return None

    valid = verify_password(secret, user.secret_hash)

    if not valid:
        return None

    return user


async def login_user(
    db: AsyncSession,
    username: str,
    secret: str
):

    user = await authenticate_user(
        db,
        username,
        secret
    )

    if not user:
        return None

    token = create_access_token(
        subject=str(user.id),
        token_version=user.token_version
    )

    refresh_token = create_refresh_token(
        subject=str(user.id),
        token_version=user.token_version
    )

    return {
        "access_token": token,
        "refresh_token": refresh_token,
        "token_type": "bearer"
    }