#!/bin/bash
# apply-pending-imports.sh — Poller filesystem-driven que aplica JSONs pendientes.
#
# Itera /home/bewpro22/.../storage/app/reseller-imports/*.json. Cada filename =
# {airtable_record_id}.json. Para cada uno:
#   1. Lookup en Airtable Projects por record_id → obtiene Cpanel_User + status
#   2. Si tenant existe + status ∈ {On Development, Active} → invoca apply-reseller-import.sh
#   3. Si import OK, el script atómico borra el stash → siguiente run no lo procesa
#
# Ventaja vs filter Airtable: NO depende de campos custom (Has_Import_JSON, Import_Status)
# que pueden no existir en la tabla. El stash file es source of truth.
#
# Llamado por cron cada minuto via flock para evitar concurrencia.

set -uo pipefail

# Cargar credenciales
if [[ -f /root/scripts/.airtable.env ]]; then
  set -a
  source /root/scripts/.airtable.env
  set +a
fi

AIRTABLE_TOKEN="${AIRTABLE_TOKEN:-}"
AIRTABLE_BASE_ID="${AIRTABLE_BASE_ID:-}"
PROJECTS_TABLE="${AIRTABLE_PROJECTS_TABLE:-tblzCgJZCbbt5j13Q}"
APPLY_SCRIPT="${APPLY_SCRIPT:-/root/scripts/apply-reseller-import.sh}"
STASH_DIR="${STASH_DIR:-/home/bewpro22/public_html/bewpro/storage/app/reseller-imports}"

if [[ -z "$AIRTABLE_TOKEN" || -z "$AIRTABLE_BASE_ID" ]]; then
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: AIRTABLE creds no configurados"
  exit 1
fi
if [[ ! -x "$APPLY_SCRIPT" ]]; then
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: ${APPLY_SCRIPT} no ejecutable"
  exit 1
fi
if [[ ! -d "$STASH_DIR" ]]; then
  # Sin stash dir → nada que hacer (silencioso, exit normal)
  exit 0
fi

# Listar stash files
PENDING_FILES=$(find "$STASH_DIR" -maxdepth 1 -name 'rec*.json' -type f 2>/dev/null || true)

if [[ -z "$PENDING_FILES" ]]; then
  exit 0  # Sin pending — silencioso
fi

COUNT=$(echo "$PENDING_FILES" | wc -l | tr -d ' ')
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ${COUNT} stash file(s) pendiente(s)"

# Procesar cada stash file
while IFS= read -r STASH_FILE; do
  [[ -z "$STASH_FILE" ]] && continue

  RECORD_ID=$(basename "$STASH_FILE" .json)

  # Lookup en Airtable: tenant existe? está provisionado?
  RECORD_DATA=$(curl -s \
    -H "Authorization: Bearer ${AIRTABLE_TOKEN}" \
    "https://api.airtable.com/v0/${AIRTABLE_BASE_ID}/${PROJECTS_TABLE}/${RECORD_ID}" 2>/dev/null)

  PARSE=$(echo "$RECORD_DATA" | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    f = d.get('fields', {})
    cpanel = (f.get('Cpanel_User') or '').strip()
    status = (f.get('Pipeline_Status') or '').strip()
    if d.get('error'):
        print(f\"ERROR|{d['error'].get('message','airtable error')}\")
    elif not cpanel:
        print('SKIP|cpanel_user vacío — tenant aún no provisionado')
    elif status not in ('On Development', 'Active'):
        print(f'SKIP|status={status} — todavía no provisionado')
    else:
        print(f'OK|{cpanel}')
except Exception as e:
    print(f'PARSE_ERROR|{e}')
")
  STATUS=$(echo "$PARSE" | cut -d'|' -f1)
  PAYLOAD=$(echo "$PARSE" | cut -d'|' -f2-)

  case "$STATUS" in
    OK)
      CPANEL_USER="$PAYLOAD"
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] → ${RECORD_ID} (${CPANEL_USER}) — aplicando..."
      "$APPLY_SCRIPT" "$RECORD_ID" "$CPANEL_USER" "$AIRTABLE_TOKEN" "$AIRTABLE_BASE_ID" 2>&1 | sed "s/^/    /"
      ;;
    SKIP)
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] ↷ ${RECORD_ID} skip: ${PAYLOAD}"
      ;;
    ERROR|PARSE_ERROR)
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✗ ${RECORD_ID} ${STATUS}: ${PAYLOAD}"
      ;;
  esac

done <<< "$PENDING_FILES"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Poll done."
