from datetime import datetime, timedelta
from typing import Annotated, Union

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession

from .db import SessionLocal
from . import orm_models, pydantic_schemas
from .config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")


async def get_session() -> AsyncSession:
    async with SessionLocal() as session:
        yield session


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.hash(password)


async def get_user_by_nickname(db: Annotated[AsyncSession, Depends(get_session)], nickname: str):
    query = await db.execute(select(orm_models.User).where(orm_models.User.nickname == nickname))
    user_with_required_nickname = query.scalars().first()
    if user_with_required_nickname:
        return user_with_required_nickname
    return None


async def get_user_by_id(db: Annotated[AsyncSession, Depends(get_session)], user_id: int):
    query = await db.execute(select(orm_models.User).where(orm_models.User.id == user_id))
    user_with_required_id = query.scalars().first()
    if user_with_required_id:
        return user_with_required_id
    return None
    

async def authenticate_user(db: Annotated[AsyncSession, Depends(get_session)], nickname: str, password: str):
    user = await get_user_by_nickname(db=db, nickname=nickname)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):
        return False
    return user


def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


async def get_current_user(db: Annotated[AsyncSession, Depends(get_session)], token: Annotated[str, Depends(oauth2_scheme)]):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id: int = payload.get("user_id")
        if user_id is None:
            raise credentials_exception
        token_data = pydantic_schemas.TokenData(user_id=user_id)
    except JWTError:
        raise credentials_exception
    user = await get_user_by_id(db, user_id=token_data.user_id)
    if user is None:
        raise credentials_exception
    return pydantic_schemas.User(id=user.id, nickname=user.nickname, name=user.name, surname=user.surname,
        disabled=user.disabled, items=user.announcements, reg_date=user.reg_date, points=user.points)


def get_current_active_user(
    current_user: Annotated[pydantic_schemas.User, Depends(get_current_user)]
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user
