
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, status
from datetime import timedelta

from app.core.auth import authenticate_user, sign_up_new_user
from app.core import security,tenantCacheService
from app.core.dbmanager import get_db
from sqlalchemy.orm  import Session

auth_router = r = APIRouter()


@r.post("/token")
async def login(request: Request,db:Session= Depends(get_db) ,form_data: OAuth2PasswordRequestForm = Depends()):
    if not db :
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user = authenticate_user(db, form_data.username, form_data.password)

    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="abcIncorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(
        minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES
    )
    if user.is_superuser:
        roles = "super"
        permissions = "ALL"
    else:
        roles = ";".join(role.name for role in user.roles)
        perlst = [perm.privilege for role in user.roles for perm in role.permissions]
        permissions =";".join(list(set(perlst)))
    
    access_token = security.create_access_token(
        data={"sub": user.id,"roles":roles,"permissions": permissions,"tenant":user.tenantid,},
        expires_delta=access_token_expires,
    )
    
    request.state.user = user.id 

    return JSONResponse(
        status_code=200,
        content={"access_token": access_token, "token_type": "bearer","user_name":user.first_name + " " + user.last_name}
    )

@r.post("/signup")
async def signup(
    firstname:str, lastname:str,
    db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
):
    user = sign_up_new_user(db, form_data.username, form_data.password,firstname,lastname)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Account already exists",
            headers={"WWW-Authenticate": "Bearer"},
        )

    access_token_expires = timedelta(
        minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES
    )
    if user.is_superuser:
        permissions = "admin"
    else:
        permissions = "user"
    access_token = security.create_access_token(
        data={"sub": user.id, "permissions": permissions},
        expires_delta=access_token_expires,
    )

    return {"access_token": access_token, "token_type": "bearer","user_name":user.first_name + " " + user.last_name}
