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

export default defineEventHandler(async (event): Promise<CodevFiche> => {
  const config = useRuntimeConfig()
  const tableId = config.codevTableId
  const baseId = config.codevBaseId || 'pipilvsi7dibo80'
  const id = getRouterParam(event, 'id')

  if (!tableId || !id) {
    throw createError({ statusCode: 400, message: 'Parametre manquant' })
  }

  const url = `${config.nocodbUrl}/api/v1/db/data/noco/${baseId}/${tableId}/${id}`

  const r: any = await $fetch(url, {
    headers: { 'xc-token': config.nocodbToken },
  }).catch(() => null)

  if (!r) {
    throw createError({ statusCode: 404, message: 'Fiche introuvable' })
  }

  return {
    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 || '',
  }
})
