#!/usr/bin/env bash
# Build only. Never pulls code, migrates, restarts, edits env or contacts WhatsApp.
# Run under the app owner, not root, after validating the new host's actual path.
set -euo pipefail
TARGET_DIR="${1:?Usage: bash deploy/build-product-assets.sh /absolute/app/path [--check]}"
[[ "$TARGET_DIR" = /* && -d "$TARGET_DIR" ]] || { echo 'Absolute existing app directory required.' >&2; exit 1; }
cd -- "$TARGET_DIR"
[[ -f artisan && -f composer.json && -f package-lock.json && -f resources/js/Pages/Product/Inbox.vue ]] || { echo 'Not the CRM application.' >&2; exit 1; }
[[ ! -e public/hot ]] || { echo 'Refusing: public/hot points clients at a dev server. Review it manually.' >&2; exit 1; }
command -v node >/dev/null
command -v npm >/dev/null
node -e 'if (Number(process.versions.node.split(".")[0]) < 20) process.exit(1)'
if [[ "${2:-}" == '--check' ]]; then echo 'Build preflight passed; no changes made.'; exit 0; fi
[[ -z "${2:-}" ]] || { echo 'Unknown argument.' >&2; exit 1; }
npm ci --no-audit --no-fund
npm run build
node -e 'const fs=require("fs"); const m=JSON.parse(fs.readFileSync("public/build/manifest.json","utf8")); const a=m["resources/js/app.js"]; if(!a || !fs.existsSync("public/build/"+a.file)) throw Error("Missing app bundle"); for(const p of ["public/fonts/IBMPlexSansArabic-Regular.ttf","public/fonts/IBMPlexSansArabic-SemiBold.ttf"]) if(!fs.existsSync(p)) throw Error("Missing font");'
echo 'Product assets built. No migration or service restart was performed.'
