import type { Context } from "./context";
import { TRPCError, initTRPC } from "@trpc/server";
import { ZodError } from "zod";

export const t = initTRPC.context<Context>().create({
	errorFormatter({ shape, error }) {
		return {
			...shape,
			data: {
				...shape.data,
				zodError:
					error.cause instanceof ZodError
						? error.cause.flatten()
						: null,
			},
		};
	},
});

export const createTRPCRouter = t.router;

export const publicProcedure = t.procedure;

const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
	if (!ctx.session || !ctx.session.userId || !ctx.user || !ctx.user.email) {
		throw new TRPCError({ code: "UNAUTHORIZED" });
	}
	return next({ ctx: { session: { ...ctx.session }, user: { ...ctx.user } } });
});

export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
