import type { YogaInitialContext } from "graphql-yoga";
import type { FastifyRequest, FastifyReply } from "fastify";
import type { Context } from "./builder";
import { getSession } from "../lib/auth";
import { db } from "../db/connection";
import { redis } from "../lib/auth";

type ServerContext = {
  req: FastifyRequest;
  reply: FastifyReply;
  db: typeof db;
  redis: typeof redis;
};

export async function buildContext(ctx: YogaInitialContext & ServerContext): Promise<Context> {
  const request = ctx.request;
  const cookieHeader = request.headers.get("cookie") || "";

  // Parse session_token from cookies
  const cookies = Object.fromEntries(
    cookieHeader.split(";").map((c) => {
      const [k, ...v] = c.trim().split("=");
      return [k.trim(), v.join("=")];
    }),
  );

  const token = cookies["session_token"];
  const currentUser = token ? await getSession(token) : null;

  return {
    db: ctx.db || db,
    redis: ctx.redis || redis,
    currentUser,
    request,
    reply: ctx.reply,
  };
}
