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

import { getStaff } from '~/apis/admin/get-staff'
import { AUTH_PAGES } from '~/configs/pages'
import { AdminDefaultLayout } from '~/layouts/admin/default'
import { handleCookie } from '~/libs/cookies'
import { setStaffLogoutHeaders } from '~/libs/logout-header.server'

import type { Route } from './+types/_admin.lg-admin'

export const loader = async ({ request }: Route.LoaderArgs) => {
  const { staffToken } = await handleCookie(request)
  const { pathname } = new URL(request.url)
  const isAuthPage = AUTH_PAGES.includes(pathname)
  let staffData

  if (staffToken) {
    try {
      const { data } = await getStaff({
        accessToken: staffToken,
      })
      staffData = data
    } catch (error) {
      if (error instanceof XiorError && error.response?.status === 401) {
        setStaffLogoutHeaders()
      }
    }
  }

  if (!isAuthPage && !staffToken) {
    throw redirect('/lg-admin/login')
  }

  if (isAuthPage && staffToken) {
    throw redirect('/lg-admin')
  }

  return {
    staffData,
  }
}

const AdminLayout = () => {
  return (
    <AdminDefaultLayout>
      <Outlet />
    </AdminDefaultLayout>
  )
}

export default AdminLayout
