import { queryCollection } from '@nuxt/content/server'

export default defineCachedEventHandler(async (event) => {
  const result = await queryCollection(event, 'experiences')
    .where('extension', '=', 'md')
    .all()

  if (result.length === 0) {
    throw createError({ statusCode: 404, statusMessage: 'Experience records not found' })
  }

  return result
    .sort((a, b) => new Date(b.meta.startDate as string).getTime() - new Date(a.meta.startDate as string).getTime())
    .map(exp => ({
      title: exp.meta.title,
      company: exp.meta.company,
      companyUrl: exp.meta.companyUrl,
      startDate: exp.meta.startDate,
      endDate: exp.meta.endDate,
      location: exp.meta.location,
      description: exp.meta.description
    }))
},
{
  maxAge: 60 * 60 * 24,
  name: 'experiences'
})
