import type { Portfolio } from '~~/types'
import { getPortfolio, savePortfolio } from '../../../lib/portfolio-store'

export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id')!
  const existing = await getPortfolio(id)
  if (!existing) throw createError({ statusCode: 404, statusMessage: 'Portfolio introuvable' })

  const body = await readBody<Portfolio>(event)
  if (!body || !Array.isArray(body.pages) || typeof body.name !== 'string') {
    throw createError({ statusCode: 400, statusMessage: 'Portfolio invalide' })
  }
  // L'id et les dates de création restent ceux du serveur.
  const portfolio: Portfolio = {
    ...existing,
    ...body,
    id,
    createdAt: existing.createdAt,
  }
  return await savePortfolio(portfolio)
})
