import { getPayload } from 'payload'
import configPromise from '@payload-config'
import { Car, Media } from '@/payload-types'
import { ContactSectionForm } from '@/globals/ContactForm/Component'
import { CatalogContent } from '@/components/pages/Catalog/CatalogContent'
import { VehicleApiResponse } from '@/lib/types/api/vehicle'
import { customFetch } from '@/lib/utils/apiClient'
import { getCurrentLocale } from '@/locales/server'


export default async function CatalogPage() {
  const payload = await getPayload({ config: configPromise })
  const locale = await getCurrentLocale()

  const { bg, title } = await payload.findGlobal({
    slug: 'catalog',
    depth: 1,
    locale,
  })

  // const result = await payload.find({
  //   collection: 'cars',
  //   limit: 16,
  //   pagination: false,
  //   depth: 2,
  // })

  // const docs = result.docs as Car[]

  let vehicles: VehicleApiResponse = []
  try {
    const vehicleResponse = await customFetch('https://api.rentsyst.com/v2/vehicle', true, 'GET')
    const data: VehicleApiResponse = await vehicleResponse.json()
    vehicles = Array.isArray(data) ? data : []
  } catch {
    console.error('Failed to fetch vehicles from rentsyst API')
  }

  return (
    <>
      <CatalogContent
        vehicles={vehicles}
        bg={bg as Media}
        title={title}
        // initialCars={docs}
      />
      <ContactSectionForm />
    </>
  )
}
