#!/usr/bin/env nu
# Triggered by pipeline: image-approved
# Subject: ${NATS_NAMESPACE}.content.image-approved
#
# Env vars set by the executor:
#   PIPELINE_EVENT   — actual NATS subject
#   PIPELINE_PAYLOAD — raw JSON body
#
# Expected payload: { content_type: string, language: string, id: string, image_type: string }

let event   = $env.PIPELINE_EVENT
let payload = $env.PIPELINE_PAYLOAD | from json

let ct         = $payload | get --optional content_type | default ""
let lang       = $payload | get --optional language      | default ""
let id         = $payload | get --optional id            | default ""
let image_type = $payload | get --optional image_type    | default ""

print $"[on-image-approved] event=($event) type=($ct) lang=($lang) id=($id) image_type=($image_type)"

if $ct == "" or $lang == "" {
    print "[on-image-approved] missing content_type or language in payload — skipping"
    exit 0
}

# Sync approved images to the public static tree so they are served over HTTP.
let copy_script = "scripts/content/copy-content-images.nu"

if not ($copy_script | path exists) {
    print $"[on-image-approved] copy script not found at ($copy_script) — skipping sync"
    exit 0
}

print $"[on-image-approved] syncing images for ($ct)/($lang)"
run-external "nu" $copy_script "--type" $ct "--lang" $lang

# Mirror site/public → target/site so the dev server serves the image immediately
# without requiring a full cargo-leptos rebuild.
if ("target/site" | path exists) {
    print "[on-image-approved] syncing site/public → target/site"
    run-external "rsync" "-a" "--exclude=.DS_Store" "site/public/" "target/site/"
}
