
import { defineMiddleware } from "astro:middleware";
import { getAuth } from "firebase-admin/auth";
import { app } from "../firebase/server";

export async function onRequest(
  context: {
    locals: { name: string, userId: string, email: string },
    cookies: { get: (arg0: string) => any };
  },
  next: () => any,
) {
  // intercept data from a request
  // optionally, modify the properties in `locals`
  //context.locals.user.name = "John Wick";
  const auth = getAuth(app);

  try {
const session = context.cookies.get("__session")?.value;

if (session) {
  const decodedCookie = await auth.verifySessionCookie(session);
const user = await auth.getUser(decodedCookie.uid);
context.locals.name = user.displayName ? user.displayName : "";
context.locals.userId = user.uid;
context.locals.email = user.email ? user.email : "";
}
  

  //const sessionCookie = Astro.cookies.get("__session")?.value;

// const decodedCookie = await auth.verifySessionCookie(session);
// const user = await auth.getUser(decodedCookie.uid);
// console.log("user?", user)
// context.locals.name = user.displayName ? user.displayName : "";
// context.locals.userId = user.uid;
// context.locals.email = user.email ? user.email : "";
  } catch {
    console.log("error!")
  }
  

  // return a Response or the result of calling `next()`
  return next();
}
