#!/usr/bin/env bash
# Runs the test suite against a real MySQL database, inside the app container.
#
#   scripts/run_tests.sh              # rebuild the test DB, then run everything
#   scripts/run_tests.sh --no-rebuild # skip the rebuild (faster, if schema is unchanged)
#   scripts/run_tests.sh --filter AuthTest
#
# Why root: the test database (axioma_test) is disposable and created fresh by
# `artisan test:prepare-db`, but the app's own MySQL user only has rights on
# the real `axioma` database, so it cannot see — let alone create — the test
# one. Granting it rights on a throwaway database would be more moving parts
# than just using the credentials that already exist. Read from the repo's own
# root .env, same as scripts/backup_db.sh.
#
# The unit tests don't need any of this (they extend PHPUnit's TestCase
# directly and never touch a database); this exists for the feature tests.

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REBUILD=1
PHPUNIT_ARGS=()

while [ $# -gt 0 ]; do
    case "$1" in
        --no-rebuild) REBUILD=0; shift ;;
        *) PHPUNIT_ARGS+=("$1"); shift ;;
    esac
done

# shellcheck disable=SC1091
source "$REPO_ROOT/.env"

: "${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD must be set in .env}"

COMPOSE=(docker compose -f "$REPO_ROOT/docker-compose.yml")

# APP_ENV has to be a real environment variable here. docker-compose.yml sets
# APP_ENV on the app service, and neither phpunit.xml's <env> entry nor
# force="true" overrides a variable the container already has — the suite then
# runs as `development`, CSRF verification stays on, and every POST test fails
# with 419.
TEST_ENV=(
    -e APP_ENV=testing
    -e DB_NAME=axioma_test
    -e DB_USER=root
    -e "DB_PASS=$MYSQL_ROOT_PASSWORD"
)

if [ "$REBUILD" -eq 1 ]; then
    echo "== Rebuilding axioma_test from docker/mysql/init/*.sql"
    "${COMPOSE[@]}" exec -T "${TEST_ENV[@]}" app sh -c 'cd laravel && php artisan test:prepare-db' \
        | tail -3
fi

echo "== Running the suite"
"${COMPOSE[@]}" exec -T "${TEST_ENV[@]}" app sh -c \
    "cd laravel && php vendor/bin/phpunit ${PHPUNIT_ARGS[*]:-}"
