import { Outlet } from 'react-router'
import { XiorError } from 'xior'

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 { setUserLogoutHeaders } from '~/libs/logout-header.server'

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

export const loader = async ({ request }: Route.LoaderArgs) => {
  const { userToken } = await handleCookie(request)
  let userData
  if (userToken) {
    try {
      const { data } = await getUser({
        accessToken: userToken,
      })
      userData = data
    } catch (error) {
      if (error instanceof XiorError && error.response?.status === 401) {
        setUserLogoutHeaders()
      }
    }
  }
  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
