import { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
import pb from "./pocketbase";
import { redirect } from "next/navigation";

export const getUserFromCookie = async (cookies: ReadonlyRequestCookies) => {
  const cookie = cookies.get('pb_auth');
  if (!cookie) {
    redirect('/');
    //throw new Error("No authenticated user");
  } else {
    pb.authStore.loadFromCookie(cookie?.value || '');
    return pb.authStore.model;
  }
}

export const isAuthenticated = async (cookieStore: ReadonlyRequestCookies) => {
  const cookie = cookieStore.get('pb_auth');
  if(!cookie) return false;
  pb.authStore.loadFromCookie(cookie?.value || '');
  return pb.authStore.isValid || false;
}