#!/usr/bin/env bash
#
# Run the HMRC feature tests once per fraud-prevention "device" profile, so HMRC
# sees fraud-prevention headers submitted from different hardware across the
# review window. Each run submits real requests to the HMRC sandbox using the
# selected profile's Gov-Client-* header values.
#
# Usage (from the basetax.api directory):
#   tests/Feature/Hmrc/run-fph-profiles.sh                 # all profiles, full HMRC suite
#   tests/Feature/Hmrc/run-fph-profiles.sh "chrome-windows"     # one profile
#   tests/Feature/Hmrc/run-fph-profiles.sh "" tests/Feature/Hmrc/Obligations  # all profiles, one path
#
# Profiles are defined in tests/Feature/Hmrc/Support/FraudPreventionDeviceProfiles.php.
# To submit as different USERS as well, run each invocation with a different
# HMRC_TEST_AUTH_TOKEN (a separate HMRC sandbox test user).
set -euo pipefail

cd "$(dirname "$0")/../../.." # → basetax.api

# Profiles: use the argument if given, else enumerate them from the PHP class so
# this stays in sync with FraudPreventionDeviceProfiles.
PROFILES="${1:-}"
if [ -z "$PROFILES" ]; then
  PROFILES="$(php -r 'require "vendor/autoload.php"; echo implode(" ", \Tests\Feature\Hmrc\Support\FraudPreventionDeviceProfiles::keys());' 2>/dev/null || true)"
fi
if [ -z "$PROFILES" ]; then
  PROFILES="chrome-macbook firefox-macbook chrome-windows"
fi

TEST_PATH="${2:-tests/Feature/Hmrc}"

echo "Running HMRC tests for profiles: $PROFILES"
echo "Test path: $TEST_PATH"
echo

# This project is Laravel 5.6 / PHPUnit 6.5 — there is no `php artisan test`
# command, so run the PHPUnit binary directly.
PHPUNIT="./vendor/bin/phpunit"
if [ ! -x "$PHPUNIT" ]; then
  echo "Could not find $PHPUNIT — run 'composer install' first." >&2
  exit 1
fi

for profile in $PROFILES; do
  echo "======================================================================"
  echo "  FPH device profile: $profile"
  echo "======================================================================"
  FPH_TEST_DEVICE_PROFILE="$profile" "$PHPUNIT" "$TEST_PATH" || {
    echo "!! Tests failed for profile '$profile'"
  }
  echo
done

echo "Done. Each profile above submitted its headers to the HMRC validator via"
echo "the FraudPreventionHeadersService; check the hmrc_fraud_prevention_headers"
echo "table (tested_at / success / test_result) to confirm they validated clean."
