#!/bin/bash
# Minify JS and CSS assets for production deploy
# Run this before restarting nginx / gunicorn

set -e

echo "=== Minifying POS JS assets ==="
for f in /home/Autopartes/pos/static/js/*.js; do
    # Skip already-minified files to avoid generating .min.min.js
    case "$f" in
        *.min.js) continue ;;
    esac
    base=$(basename "$f" .js)
    out="/home/Autopartes/pos/static/js/${base}.min.js"
    echo "  $base.js -> ${base}.min.js"
    terser "$f" -o "$out" --compress --mangle 2>/dev/null || cp "$f" "$out"
done

echo "=== Minifying POS CSS assets ==="
for f in /home/Autopartes/pos/static/css/*.css; do
    case "$f" in
        *.min.css) continue ;;
    esac
    base=$(basename "$f" .css)
    out="/home/Autopartes/pos/static/css/${base}.min.css"
    echo "  $base.css -> ${base}.min.css"
    if command -v csso >/dev/null 2>&1; then
        csso "$f" -o "$out" 2>/dev/null || cp "$f" "$out"
    else
        cp "$f" "$out"
    fi
done

echo "=== Minifying Dashboard JS assets ==="
for f in /home/Autopartes/dashboard/*.js; do
    case "$f" in
        *.min.js) continue ;;
    esac
    base=$(basename "$f" .js)
    out="/home/Autopartes/dashboard/${base}.min.js"
    echo "  $base.js -> ${base}.min.js"
    terser "$f" -o "$out" --compress --mangle 2>/dev/null || cp "$f" "$out"
done

echo "=== Minifying Dashboard CSS assets ==="
for f in /home/Autopartes/dashboard/*.css; do
    case "$f" in
        *.min.css) continue ;;
    esac
    base=$(basename "$f" .css)
    out="/home/Autopartes/dashboard/${base}.min.css"
    echo "  $base.css -> ${base}.min.css"
    if command -v csso >/dev/null 2>&1; then
        csso "$f" -o "$out" 2>/dev/null || cp "$f" "$out"
    else
        cp "$f" "$out"
    fi
done

echo "=== Done ==="
echo "Minified files ready. Nginx will serve .min.js/.min.css when available."
