#!/usr/bin/env bash
# 02-assets — build determinístico do frontend (Vite) com a imagem Node pinada.
set -Eeuo pipefail
# shellcheck source=../lib/common.sh
. "$(dirname "$0")/../lib/common.sh"

phase_begin "02-assets"

if [ ! -f "$ROOT/package.json" ] || [ ! -f "$ROOT/package-lock.json" ]; then
    warn "package.json/package-lock.json ausentes — nenhum asset a construir."
    phase_end
    exit 0
fi

# `npm ci` é reprodutível (lockfile) e roda como o dono do checkout (sem root no bind).
run docker run --rm \
    --user "$(id -u):$(id -g)" \
    -e HOME=/tmp \
    -v "$ROOT":/app"$MOUNT_LABEL" \
    -w /app \
    "$NODE_IMAGE" \
    sh -c 'npm ci && npm run build'

if [ "$DRY_RUN" = 0 ] && [ ! -f "$ROOT/public/build/manifest.json" ]; then
    die "build de assets não produziu public/build/manifest.json"
fi

# O runtime não usa node: o artefato é public/build. Remover node_modules depois do build
# evita consumir a cota do home (cPanel/LVE) que o PGDATA precisa na fase seguinte.
if [ "$DRY_RUN" = 0 ] && [ -d "$ROOT/node_modules" ]; then
    log "removendo node_modules (artefato de build; libera a cota do home)"
    find "$ROOT/node_modules" -mindepth 1 -delete 2>/dev/null || warn "não foi possível remover todo o node_modules"
    rmdir "$ROOT/node_modules" 2>/dev/null || true
fi

phase_end
