#!/usr/bin/env bash
# Generate cached thumbnails (40px and 200px) for every uploaded product image.
#
# Pre-generates thumbnails in each app's public/uploads/thumbs/<size>/ directory
# so Next.js serves them as static files with Cache-Control: public, max-age=31536000.
#
# Run after every upload, as part of sync_uploads in monolith.sh, or on demand.
#
# Usage:
#   ./scripts/generate-thumbnails.sh

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# Find a node_modules that contains sharp
SHARP_DIR=""
for dir in "$PROJECT_DIR/apps/admin" "$PROJECT_DIR/frontend" "$PROJECT_DIR/storefront"; do
  if [[ -d "$dir/node_modules/sharp" ]]; then
    SHARP_DIR="$dir"
    break
  fi
done

if [[ -z "$SHARP_DIR" ]]; then
  echo "[FAIL] sharp not found; install with: cd project/apps/admin && npm install sharp" >&2
  exit 1
fi

cd "$SHARP_DIR"
exec node "$SCRIPT_DIR/generate-thumbnails.mjs"