import { initTRPC } from "@trpc/server"

import { env } from "@/env/server"

import {
  badRequestError,
  sessionExpiredError,
  unauthorizedError,
} from "./errors/trpc"
import { transformer } from "./transformer"

import type { Meta } from "@/types/trpc/meta"
import type { Context } from "./context"

const t = initTRPC.context<Context>().meta<Meta>().create({ transformer })

export const { createCallerFactory, mergeRouters, router } = t
export const publicProcedure = t.procedure
export const contentstackProcedure = t.procedure.use(async function (opts) {
  if (!opts.ctx.uid) {
    throw badRequestError("Missing UID in tRPC context")
  }

  return opts.next({
    ctx: {
      uid: opts.ctx.uid,
    },
  })
})
export const protectedProcedure = t.procedure.use(async function (opts) {
  const authRequired = opts.meta?.authRequired ?? true
  const session = await opts.ctx.auth()

  if (!authRequired && env.NODE_ENV === "development") {
    console.info(
      `❌❌❌❌ You are opting out of authorization, if its done on purpose maybe you should use the publicProcedure instead. ❌❌❌❌`
    )
    console.info(`path: ${opts.path} | type: ${opts.type}`)
  }

  if (session?.error === "RefreshAccessTokenError") {
    throw sessionExpiredError()
  }

  if (!session?.user) {
    throw unauthorizedError()
  }

  return opts.next({
    ctx: {
      session,
    },
  })
})
