import { initTRPC } from "@trpc/server"
import { z } from "zod"

import { parseRefId } from "@/utils/refId"

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

export function createRefIdPlugin() {
  const t = initTRPC.context<Context>().meta<Meta>().create()

  return {
    toConfirmationNumber: t.procedure
      .input(
        z.object({
          refId: z.string(),
        })
      )
      .use(({ input, next }) => {
        const { confirmationNumber } = parseRefId(input.refId)
        return next({
          ctx: {
            confirmationNumber,
          },
        })
      }),
    toConfirmationNumbers: t.procedure
      .input(
        z.object({
          refIds: z.array(z.string()),
        })
      )
      .use(({ input, next }) => {
        const confirmationNumbers = input.refIds.map((refId) => {
          const { confirmationNumber } = parseRefId(refId)
          return confirmationNumber
        })

        return next({
          ctx: {
            confirmationNumbers,
          },
        })
      }),
  }
}
