import type { Route } from './+types/route'

import { redirect } from 'react-router'

import { userContext } from '@repo/auth/context'
import { authMiddleware } from '@repo/auth/middleware/auth'
import { request as req } from '@repo/util/request'

export const middleware: Route.MiddlewareFunction[] = [authMiddleware]

export async function loader({ context, request }: Route.ActionArgs) {
  const user = context.get(userContext)

  const r = await req({
    url: `/users/${user.sub}/orgs`,
    request,
    context
  })

  if (!r.ok) {
    throw new Response(await r.text(), { status: r.status })
  }

  const { items = [] } = (await r.json()) as { items: { sk: string }[] }
  const [{ sk } = {}] = items

  if (sk) {
    const [_, id] = sk.split('#')
    throw redirect(`/${id}/main`)
  }

  throw new Response(null, { status: 401 })
}
