#!/bin/bash
# =============================================================================
# Auto-close cron - belt-and-braces backup to the in-process @nestjs/schedule
# job. Runs every 30 min via PM2 (see ecosystem.config.js).
#
# Reads CRON_SECRET from .env and calls /api/internal/auto-close.
# =============================================================================

set -euo pipefail

ENV_FILE="/www/wwwroot/vihar/.env"

if [ ! -f "$ENV_FILE" ]; then
  echo "ERROR: $ENV_FILE not found" >&2
  exit 1
fi

# Source CRON_SECRET safely (only that var)
CRON_SECRET=$(grep -E '^CRON_SECRET=' "$ENV_FILE" | head -1 | cut -d'=' -f2- | tr -d '"' | tr -d "'")

if [ -z "$CRON_SECRET" ]; then
  echo "ERROR: CRON_SECRET not set in $ENV_FILE" >&2
  exit 1
fi

API_URL="http://127.0.0.1:4001/api/internal/auto-close"

response=$(curl -sS -X POST "$API_URL" \
  -H "Content-Type: application/json" \
  -H "X-Cron-Secret: $CRON_SECRET" \
  -w "\n%{http_code}" \
  --max-time 30)

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | head -n-1)

if [ "$http_code" = "201" ] || [ "$http_code" = "200" ]; then
  echo "[$(date -Iseconds)] auto-close OK: $body"
else
  echo "[$(date -Iseconds)] auto-close FAILED ($http_code): $body" >&2
  exit 1
fi
