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

import { z } from 'zod'

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

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

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(ctx.viewer)
      }
      const redirectUrl = await ctx.auth.getAuthenticationUrl({ redirectTo: decodeURIComponent(input.pageUrl) })

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