// Médias de la vue publique : sert exclusivement le snapshot figé du portfolio
// <id>, et seulement s'il est partagé publiquement (publicShare). Aucun repli
// sur le contenu live — la surface publique reste limitée à l'instantané.
import { join } from 'node:path'
import { getPortfolio } from '../../../../lib/portfolio-store'
import { serveMedia, splitMediaPath } from '../../../../lib/media'

export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id') ?? ''
  if (!/^[\w-]+$/.test(id)) {
    throw createError({ statusCode: 400, statusMessage: 'Identifiant invalide' })
  }

  const portfolio = await getPortfolio(id)
  if (!portfolio?.publicShare) {
    throw createError({ statusCode: 404, statusMessage: 'Portfolio introuvable' })
  }

  const { projectId, filename } = splitMediaPath(getRouterParam(event, 'path') ?? '')
  const query = getQuery(event)
  const width = Number(query.w) || 0
  const wantPoster = Boolean(query.poster)

  const config = useRuntimeConfig(event)
  const roots = [join(config.dataDir, 'frozen', id)]

  return serveMedia(event, { roots, projectId, filename, width, wantPoster, dataDir: config.dataDir })
})
