from types import MethodType
from pydantic import Json
from functionability.functions import queryDB
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, Response
import bcrypt, jwt

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173","http://192.168.18.55:5173","http://192.168.18.55:4173"],
    allow_credentials=True,
    allow_methods=[""],
    allow_headers=[""]
)

@app.post("/api/checkToken")
def checkTokenInDb(request :Request):
    credential=request.cookies.get("accesToken")
    if credential in queryDB("select tokens from bannedTokens where tokens = %s",(credential,)):
        return "bannedCredential"
    elif credential in queryDB("select tokens from userTokens where tokens = %s",(credential,)):
        return "validCredential"
    else:
        return False
    

@app.post("/api/loginToken")
def setTokenIfCorrect(request :Json, response :Response):
    credential=request.json
    user=credential["user"]
    pwd=credential["pwd"]
    hashedPwd=queryDB("select password from user where name = %s",(user,))
    if not bcrypt.checkpw(pwd.encode(),hashedPwd.encode()):

    userId=queryDB("select id from user where name = %s",(user,))
    token = jwt.encode({
        "sub":userId,
        "exp":3600,
        "type":"access",
    }, "zxASqw!\"" , "HS256")    
    response.set_cookie("authToken",token,httponly=True,secure=False,samesite="lax",max_age=3600)
