import { z } from 'zod'

const FicheSchema = z.object({
  nom: z.string().min(2).max(50).trim(),
  besoin: z.string().min(5).max(300).trim(),
  offre: z.string().min(5).max(300).trim(),
  hashtags: z.array(z.string().max(30)).max(3).default([]),
})

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const parsed = FicheSchema.safeParse(body)

  if (!parsed.success) {
    throw createError({
      statusCode: 422,
      statusMessage: 'Validation échouée',
      data: parsed.error.flatten().fieldErrors,
    })
  }

  const config = useRuntimeConfig()
  const tableId = config.codevTableId
  const baseId = config.codevBaseId || 'pipilvsi7dibo80'

  const payload = {
    nom: parsed.data.nom,
    besoin: parsed.data.besoin,
    offre: parsed.data.offre,
    hashtags: parsed.data.hashtags
      .map((h) => h.trim().toLowerCase().replace(/^#/, ''))
      .filter(Boolean)
      .slice(0, 3)
      .join(','),
    created_at: new Date().toISOString(),
  }

  // NocoDB v1 endpoint pour INSERT (cf. submit/index.post.ts pour le pattern)
  const insertUrl = `${config.nocodbUrl}/api/v1/db/data/noco/${baseId}/${tableId}`

  let inserted: any
  try {
    inserted = await $fetch(insertUrl, {
      method: 'POST',
      headers: {
        'xc-token': config.nocodbToken,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    })
  } catch (e: any) {
    console.error('[codev/fiches.post] NocoDB insert error:', e?.message ?? e)
    throw createError({
      statusCode: 502,
      statusMessage: 'Erreur serveur, réessaie',
    })
  }

  return {
    status: 201,
    id: inserted?.Id ?? inserted?.id ?? null,
  }
})
