import { ViewerResult } from '@authentication/authentication.types'

import { z } from 'zod'

import { err, ok } from '@postxl/utils'

import { procedure, router } from '../trpc-shared'

function omit<T extends Record<string, unknown>, Key extends keyof T>(obj: T, key: Key): Omit<T, Key> {
  const { [key]: _, ...rest } = obj
  return rest
}

export const viewer = router({
  viewer: procedure
    .input(z.object({ pageUrl: z.string().describe('The url of the active page.') }))
    .query(async ({ ctx, input }): Promise<ViewerResult> => {
      if (ctx.viewer) {
        return ok(omit(ctx.viewer, 'userInfo'))
      }
      const redirectUrl = await ctx.auth.getAuthenticationUrl({ redirectTo: decodeURIComponent(input.pageUrl) })

      return err({ type: 'redirect', redirectUrl })
    }),
})
