import { z } from 'zod'

const PatchSchema = 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 config = useRuntimeConfig()
  const tableId = config.codevTableId
  const baseId = config.codevBaseId || 'pipilvsi7dibo80'
  const id = getRouterParam(event, 'id')
  const body = await readBody(event)

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

  const parsed = PatchSchema.safeParse(body)
  if (!parsed.success) {
    throw createError({
      statusCode: 422,
      statusMessage: 'Validation echouee',
      data: parsed.error.flatten().fieldErrors,
    })
  }

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

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

  try {
    await $fetch(url, {
      method: 'PATCH',
      headers: {
        'xc-token': config.nocodbToken,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    })
  } catch (e: any) {
    console.error('[codev/fiches.patch] NocoDB patch error:', e?.message ?? e)
    throw createError({ statusCode: 502, statusMessage: 'Erreur serveur' })
  }

  return { status: 200, ok: true }
})
