#!/usr/bin/env bash
#
# crm_smoke_test.sh — Post-deployment smoke test for the E-Factor CRM upgrade.
#
# Logs in with Sanctum bearer auth, then hits each key CRM read endpoint and
# reports PASS/FAIL. An optional --write pass creates, reads back, and archives
# a throwaway lead to exercise the write path.
#
# USAGE
#   BASE_URL=https://efector.hostingaipl.xyz/public/api \
#   EMAIL=you@example.com PASSWORD='secret' \
#   ./crm_smoke_test.sh [--write]
#
# ENV VARS
#   BASE_URL   API base (default: https://efector.hostingaipl.xyz/public/api)
#   EMAIL      Login identifier — email or phone (REQUIRED)
#   PASSWORD   Login password (REQUIRED)
#
# FLAGS
#   --write    Also run the guarded write pass (create -> read -> delete a lead)
#   -h|--help  Show this help
#
# EXIT CODE
#   0  all checks passed
#   1  one or more hard failures (or bad usage / login failure)
#
# NOTE: never commit real credentials. Pass them via env vars only.

set -u

# ── Configuration ────────────────────────────────────────────────────────────
BASE_URL="${BASE_URL:-https://efector.hostingaipl.xyz/public/api}"
EMAIL="${EMAIL:-}"
PASSWORD="${PASSWORD:-}"
DO_WRITE=0

# ── Arg parsing ──────────────────────────────────────────────────────────────
usage() {
  sed -n '2,30p' "$0" | sed 's/^#\{0,1\} \{0,1\}//'
}

for arg in "$@"; do
  case "$arg" in
    --write) DO_WRITE=1 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown argument: $arg" >&2; usage; exit 1 ;;
  esac
done

if [ -z "$EMAIL" ] || [ -z "$PASSWORD" ]; then
  echo "ERROR: EMAIL and PASSWORD env vars are required." >&2
  echo >&2
  usage >&2
  exit 1
fi

# ── Optional jq ──────────────────────────────────────────────────────────────
HAVE_JQ=0
if command -v jq >/dev/null 2>&1; then HAVE_JQ=1; fi

# ── Formatting helpers ───────────────────────────────────────────────────────
BOLD=""; RED=""; GREEN=""; YELLOW=""; RESET=""
if [ -t 1 ]; then
  BOLD="$(printf '\033[1m')"; RED="$(printf '\033[31m')"
  GREEN="$(printf '\033[32m')"; YELLOW="$(printf '\033[33m')"
  RESET="$(printf '\033[0m')"
fi

PASS_COUNT=0
FAIL_COUNT=0
TOTAL_COUNT=0

hr() { printf '%s\n' "----------------------------------------------------------------"; }

# ── Login ────────────────────────────────────────────────────────────────────
echo "${BOLD}E-Factor CRM smoke test${RESET}"
echo "Base URL : $BASE_URL"
echo "User     : $EMAIL"
echo "jq       : $([ "$HAVE_JQ" -eq 1 ] && echo present || echo 'absent (using grep/sed fallback)')"
echo "Write pass: $([ "$DO_WRITE" -eq 1 ] && echo ENABLED || echo disabled)"
hr

# The login route accepts a 'login' field (email OR phone) plus 'password'.
LOGIN_BODY="$(printf '{"login":"%s","password":"%s"}' "$EMAIL" "$PASSWORD")"
LOGIN_RESP="$(curl -sS -X POST "$BASE_URL/auth/login" \
  -H 'Content-Type: application/json' -H 'Accept: application/json' \
  -d "$LOGIN_BODY" 2>/dev/null)"

extract_token() {
  # Reads JSON on stdin, prints the bearer token if present.
  # Handles {"token":"..."} and {"data":{"token":"..."}}.
  if [ "$HAVE_JQ" -eq 1 ]; then
    printf '%s' "$1" | jq -r '.token // .data.token // empty' 2>/dev/null
  else
    printf '%s' "$1" \
      | grep -o '"token"[[:space:]]*:[[:space:]]*"[^"]*"' \
      | head -n1 \
      | sed -E 's/.*"token"[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/'
  fi
}

TOKEN="$(extract_token "$LOGIN_RESP")"

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
  echo "${RED}${BOLD}LOGIN FAILED${RESET} — could not extract a bearer token."
  echo "Response was:"
  printf '%s\n' "$LOGIN_RESP" | head -c 500
  echo
  exit 1
fi
echo "${GREEN}Login OK${RESET} — bearer token acquired."
hr

AUTH_HEADER="Authorization: Bearer $TOKEN"

# ── GET check helper ─────────────────────────────────────────────────────────
# check <label> <path>
# PASS on HTTP 200, or 403 (reachable but no permission for this role).
check() {
  local label="$1" path="$2" code
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  code="$(curl -sS -o /dev/null -w '%{http_code}' \
    -H "$AUTH_HEADER" -H 'Accept: application/json' \
    "$BASE_URL$path" 2>/dev/null)"
  if [ "$code" = "200" ]; then
    PASS_COUNT=$((PASS_COUNT + 1))
    printf '%s PASS%s  %-34s [200]\n' "$GREEN" "$RESET" "$label"
  elif [ "$code" = "403" ]; then
    PASS_COUNT=$((PASS_COUNT + 1))
    printf '%s PASS%s  %-34s [403 reachable, no permission]\n' "$YELLOW" "$RESET" "$label"
  else
    FAIL_COUNT=$((FAIL_COUNT + 1))
    printf '%s FAIL%s  %-34s [%s]\n' "$RED" "$RESET" "$label" "${code:-no-response}"
  fi
}

echo "${BOLD}Read-only endpoint pass${RESET}"
check "leads/dashboard"          "/crm/leads/dashboard"
check "masters"                  "/crm/masters"
check "masters/lead-categories"  "/crm/masters/lead-categories"
check "leads"                    "/crm/leads"
check "leads/pipeline"           "/crm/leads/pipeline"
check "reports/funnel"           "/crm/reports/funnel"
check "reports/source-perf"      "/crm/reports/source-performance"
check "reports/salesperson"      "/crm/reports/salesperson"
check "reports/pipeline-ageing"  "/crm/reports/pipeline-ageing"
check "tender-calendar"          "/crm/tender-calendar"
check "leads/import-template"    "/crm/leads/import-template"
check "audit-log"                "/crm/audit-log"
hr

# ── Optional write pass (guarded) ────────────────────────────────────────────
if [ "$DO_WRITE" -eq 1 ]; then
  echo "${BOLD}Write pass (create -> read -> archive)${RESET}"

  STAMP="$(date +%Y%m%d-%H%M%S)"
  NEW_BODY="$(printf '{"lead_type":"open_market","title":"SMOKE TEST - safe to delete %s","notes":"Created by crm_smoke_test.sh, will be archived."}' "$STAMP")"

  # 1) Create
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  CREATE_RESP="$(curl -sS -X POST "$BASE_URL/crm/leads" \
    -H "$AUTH_HEADER" -H 'Content-Type: application/json' -H 'Accept: application/json' \
    -d "$NEW_BODY" 2>/dev/null)"

  if [ "$HAVE_JQ" -eq 1 ]; then
    NEW_ID="$(printf '%s' "$CREATE_RESP" | jq -r '.data.id // .id // empty' 2>/dev/null)"
  else
    NEW_ID="$(printf '%s' "$CREATE_RESP" \
      | grep -o '"id"[[:space:]]*:[[:space:]]*[0-9]\+' \
      | head -n1 | grep -o '[0-9]\+')"
  fi

  if [ -n "$NEW_ID" ] && [ "$NEW_ID" != "null" ]; then
    PASS_COUNT=$((PASS_COUNT + 1))
    printf '%s PASS%s  create lead                        [id=%s]\n' "$GREEN" "$RESET" "$NEW_ID"

    # 2) Read back
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    RB_CODE="$(curl -sS -o /dev/null -w '%{http_code}' \
      -H "$AUTH_HEADER" -H 'Accept: application/json' \
      "$BASE_URL/crm/leads/$NEW_ID" 2>/dev/null)"
    if [ "$RB_CODE" = "200" ]; then
      PASS_COUNT=$((PASS_COUNT + 1))
      printf '%s PASS%s  read back lead                     [200]\n' "$GREEN" "$RESET"
    else
      FAIL_COUNT=$((FAIL_COUNT + 1))
      printf '%s FAIL%s  read back lead                     [%s]\n' "$RED" "$RESET" "${RB_CODE:-no-response}"
    fi

    # 3) Archive (DELETE — soft-delete/archive in the API)
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    DEL_CODE="$(curl -sS -o /dev/null -w '%{http_code}' -X DELETE \
      -H "$AUTH_HEADER" -H 'Accept: application/json' \
      "$BASE_URL/crm/leads/$NEW_ID" 2>/dev/null)"
    if [ "$DEL_CODE" = "200" ] || [ "$DEL_CODE" = "204" ]; then
      PASS_COUNT=$((PASS_COUNT + 1))
      printf '%s PASS%s  archive lead                       [%s]\n' "$GREEN" "$RESET" "$DEL_CODE"
    else
      FAIL_COUNT=$((FAIL_COUNT + 1))
      printf '%s FAIL%s  archive lead                       [%s]\n' "$RED" "$RESET" "${DEL_CODE:-no-response}"
      echo "  ${YELLOW}WARNING:${RESET} throwaway lead id=$NEW_ID may need manual cleanup."
    fi
  else
    FAIL_COUNT=$((FAIL_COUNT + 1))
    printf '%s FAIL%s  create lead                        [no id returned]\n' "$RED" "$RESET"
    echo "  Response was:"
    printf '%s\n' "$CREATE_RESP" | head -c 400
    echo
  fi
  hr
fi

# ── Summary ──────────────────────────────────────────────────────────────────
echo "${BOLD}Summary:${RESET} $PASS_COUNT passed / $TOTAL_COUNT total, $FAIL_COUNT failed."
if [ "$FAIL_COUNT" -gt 0 ]; then
  echo "${RED}${BOLD}SMOKE TEST FAILED${RESET}"
  exit 1
fi
echo "${GREEN}${BOLD}SMOKE TEST PASSED${RESET}"
exit 0
