#!/usr/bin/env bash
# Railway faunamix-cron-ops: tek seferlik görev paketi (cron). Apache başlatılmaz.
# Railway cron: görev bitince süreç çıkmalı; exit 2 (mutabakat uyarısı) crash sayılmamalı.
set -uo pipefail
cd /app
# Railway Cron Runs logları stdout/stderr birleşik; Deploy/Build Logs değil.
exec 2>&1

echo "faunamix-cron-bundle: start utc=$(date -u +%Y-%m-%dT%H:%M:%SZ) pwd=$(pwd)"

PHP="${PHP_BIN:-php}"
if ! command -v "$PHP" >/dev/null 2>&1; then
  echo "faunamix-cron-bundle: php binary not found (PATH=$PATH)" >&2
  exit 127
fi

EXIT=0

"$PHP" scripts/faunamix-inventory-reconcile.php || EXIT=$?

"$PHP" scripts/reconcile-ecommerce-payments.php
pay_exit=$?
if [[ "$pay_exit" -eq 2 ]]; then
  echo "faunamix-cron-bundle: payment reconcile issue_count>0 (exit 2), cron OK"
elif [[ "$pay_exit" -ne 0 ]]; then
  EXIT=$pay_exit
fi

"$PHP" scripts/faunamix-abandoned-cart.php || EXIT=$?

echo "faunamix-cron-bundle: finished exit=$EXIT utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
exit "$EXIT"
