import { TRPCError } from "@trpc/server";
import type { NextApiRequest, NextApiResponse } from "next";
import type { Context, Session } from "~/server/api/trpc";
import type { Prettify } from "TypeHelpers.type";

export const checkCtx = (props: {
  res: NextApiResponse | undefined;
  req: NextApiRequest | undefined;
}) => {
  const { req, res } = props;
  if (!req || !res)
    throw new TRPCError({ code: "BAD_REQUEST", message: "res o req mancanti" });
};
type CtxWSession = Prettify<Context & { session: Session }>;

export const checkCtxSession = ({ ctx }: { ctx: Context }) => {
  if (!ctx.session) {
    throw new TRPCError({
      code: "UNAUTHORIZED",
      message: "Utente non autorizzato",
    });
  }
  return ctx as CtxWSession;
};

export const checkCtxAdmin = ({ ctx }: { ctx: Context }) => {
  const ckd_ctx = checkCtxSession({ ctx });
  if (!ckd_ctx.session.isAdmin) {
    throw new TRPCError({
      code: "UNAUTHORIZED",
      message: "Utente non autorizzato",
    });
  }
  return ckd_ctx as Context & {
    session: Session & {
      isAdmin: true;
    };
  };
};
