import { Outlet } from 'react-router'

import { getCategories } from '~/apis/common/get-categories'
import { getSubscriptions } from '~/apis/common/get-subscriptions'
import { getUser } from '~/apis/news/get-user'
import { NewsProvider } from '~/contexts/news'
import { NewsDefaultLayout } from '~/layouts/news/default'
import { handleCookie } from '~/libs/cookies'

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

export const loader = async ({ request }: Route.LoaderArgs) => {
  const { userToken } = await handleCookie(request)
  let userData
  if (userToken) {
    const { data } = await getUser({
      accessToken: userToken,
    })
    userData = data
  }
  const { data: subscriptionsData } = await getSubscriptions()
  const { data: categoriesData } = await getCategories()

  return {
    userData,
    subscriptionsData,
    categoriesData,
  }
}

const NewsLayout = () => {
  return (
    <NewsProvider>
      <NewsDefaultLayout>
        <Outlet />
      </NewsDefaultLayout>
    </NewsProvider>
  )
}

export default NewsLayout
