import * as cookie from "cookie";

/** @type {import('@sveltejs/kit').Handle} */
export const handle = async ({ event, resolve }) => {
  const cookieHeader = event.request.headers.get("cookie");
  const cookies = cookie.parse(cookieHeader ?? "");

  if (!cookies.session) {
    return await resolve(event);
  }

  // Esto es lo que hace pillar una sesión y que tengo que implementar con better-sqlite3
  // const session = await db.user.findUnique({
  //   where: { id: cookies.session },
  // });

  // if (session) {
  //   event.locals.user = {
  //     username: session.username,
  //     name: session.name,
  //     slug: session.slug,
  //     isAdmin: session.isAdmin,
  //   };
  // }

  return await resolve(event);
};

/**
 *
 * @param {*} param0
 * @returns
 */
export const getSession = ({ locals }) => {
  if (!locals.user) return {};

  return {
    user: {
      username: locals.user.username,
      name: locals.user.name,
      slug: locals.user.slug,
      isAdmin: locals.user.isAdmin,
    },
  };
};
