import { deleteTokenByUID, getTokenBy } from "@/models/users";
import { JWT } from "@/utils/jwt";

export async function revokeCheck(request) {
  const jwt = new JWT();
  const cookies = Object.fromEntries(
    request.cookies.getAll().map((c) => Object.values(c))
  );
  const tokenData = jwt.decodeToken(cookies.refreshToken);
  const result = await getTokenBy({ uid: tokenData.uid, revoke: false });

  if (!result) throw { name: "Forbidden" };
}

export async function removeToken(request) {
  const jwt = new JWT();
  const cookies = Object.fromEntries(
    request.cookies.getAll().map((c) => Object.values(c))
  );
  const tokenData = jwt.decodeToken(cookies.refreshToken);
  const result = await deleteTokenByUID(tokenData.uid);

  return result;
}

export async function userTokenStatus(request) {
  const jwt = new JWT();
  const cookies = Object.fromEntries(
    request.cookies.getAll().map((c) => Object.values(c))
  );
  const tokenData = jwt.decodeToken(cookies.refreshToken);
  const result = await getTokenBy({ uid: tokenData.uid });

  return !result?.revoke;
}
