import type { CodevFiche } from '~/types/codev'

export default defineEventHandler(async (event): Promise<{ list: CodevFiche[] }> => {
  const config = useRuntimeConfig()
  const tableId = config.codevTableId

  if (!tableId) {
    throw createError({ statusCode: 500, message: 'codevTableId non configuré' })
  }

  const url = `${config.nocodbUrl}/api/v2/tables/${tableId}/records?sort=created_at&limit=200`

  const data: any = await $fetch(url, {
    headers: { 'xc-token': config.nocodbToken },
  }).catch(() => ({ list: [] }))

  // Mapper chaque record NocoDB vers CodevFiche
  const list: CodevFiche[] = (data?.list ?? []).map((r: any) => ({
    id: r.Id ?? r.id,
    nom: r.nom || '',
    besoin: r.besoin || '',
    offre: r.offre || '',
    hashtags: (r.hashtags || '')
      .split(',')
      .map((h: string) => h.trim().toLowerCase().replace(/^#/, ''))
      .filter(Boolean),
    created_at: r.created_at || r.CreatedAt || new Date().toISOString(),
  }))

  return { list }
})
