#!/usr/bin/env bash
# Împachetează imaginile de referință din DB locală și le urcă pe CDN/S3 producție (înainte de DB sync).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "${SCRIPT_DIR}/common.sh"

scp_to_remote() {
  local local_file="$1"
  local remote_path="$2"
  if [[ -n "${SSH_CONFIG_FILE:-}" && -f "${SSH_CONFIG_FILE}" ]]; then
    scp -F "${SSH_CONFIG_FILE}" "${local_file}" "${DEPLOY_USER}@${DEPLOY_HOST}:${remote_path}"
  else
    scp -i "${SSH_KEY_PATH}" -P "${DEPLOY_PORT}" \
      -o "UserKnownHostsFile=${SSH_KNOWN_HOSTS}" \
      "${local_file}" "${DEPLOY_USER}@${DEPLOY_HOST}:${remote_path}"
  fi
}

run_reference_media_push() {
  if [[ "${REFERENCE_MEDIA_SYNC:-false}" != "true" ]]; then
    log "Skipping reference media CDN sync (REFERENCE_MEDIA_SYNC=false)"
    return 0
  fi

  local local_php="${LOCAL_PHP_BINARY:-php}"
  local archive="${DEPLOY_DIR}/backups/reference-images-deploy.tar.gz"
  mkdir -p "${DEPLOY_DIR}/backups"

  log "Packing reference images from local database (categories, cities, site banners, etc.)..."
  if ! (cd "${PROJECT_ROOT}" && "${local_php}" artisan media:pack-reference-images --output="${archive}"); then
    warn "media:pack-reference-images failed — continuing deploy without media push"
    return 0
  fi

  if [[ ! -s "${archive}" ]]; then
    warn "No reference image archive produced — skip CDN upload"
    return 0
  fi

  local remote_archive="/tmp/reference-images-deploy-$$.tar.gz"
  log "Uploading reference images archive to Listara (${remote_archive})..."
  scp_to_remote "${archive}" "${remote_archive}"

  local import_flags=""
  if [[ "${REFERENCE_MEDIA_DRY_RUN:-false}" == "true" ]]; then
    import_flags="--dry-run"
    log "Reference media import (dry-run only)..."
  else
    log "Importing reference images to production CDN/S3..."
  fi

  ssh_cmd "
    cd '${DEPLOY_PATH}' &&
    sudo -u www-data ${PHP_BINARY:-php} artisan media:import-reference-images '${remote_archive}' ${import_flags} &&
    rm -f '${remote_archive}'
  " || warn "Reference media import failed (DB sync may still run)"

  cp -f "${archive}" "${DEPLOY_DIR}/backups/reference-images-deploy-last.tar.gz" 2>/dev/null || true
  log "Reference media CDN sync finished"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  load_config
  run_reference_media_push
fi
