from fastapi import Depends, HTTPException, Request
from fastapi.responses import RedirectResponse
import jwt
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from model.database import get_async_session, User

SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"

async def get_current_user(request: Request,db: AsyncSession = Depends(get_async_session)):
    token = request.cookies.get("access_token")
    print(token)
    if not token:
        raise HTTPException(status_code=401, detail="Unauthorized")

    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        print(payload)
        username = payload.get("sub")
        if not username:
            raise HTTPException(status_code=401, detail="Unauthorized")
        # Получаем роль из БД
        result = await db.execute(select(User).filter(User.username == username))
        user = result.scalars().first()
        if not user:
            return RedirectResponse(url="/login")
        
        return {"username": user.username, "role": user.role}
        
    except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
        raise HTTPException(status_code=401, detail="Unauthorized")