import { getCategories } from '~/apis/common/get-categories'
import { getNews } from '~/apis/common/get-news'
import { getNewsBySlug } from '~/apis/common/get-news-by-slug'
import { APP } from '~/configs/meta'
import { handleCookie } from '~/libs/cookies'
import { NewsDetailPage } from '~/pages/news-detail'

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

export const loader = async ({ request, params }: Route.LoaderArgs) => {
  const { userToken } = await handleCookie(request)
  const { data: newsDetailData } = await getNewsBySlug({
    slug: params.slug,
    accessToken: userToken,
  })
  const { data: categoriesData } = await getCategories()
  const beritaCode = 'berita'
  const beritaCategory = categoriesData.find(
    (category) => category.code === beritaCode,
  )
  const { data: beritaNews } = await getNews({ categories: [beritaCode] })

  return {
    newsDetailData,
    beritaCategory,
    beritaNews,
  }
}

export const meta = ({ data }: Route.MetaArgs) => {
  const { newsDetailData } = data
  const metaTitle = APP.title
  const title = `${newsDetailData.title} - ${metaTitle}`

  return [
    {
      title,
    },
  ]
}

const NewsDetailLayout = () => <NewsDetailPage />

export default NewsDetailLayout
