#!/bin/sh

# Configuration des paramètres de la base de données
DB_USER="root"
DB_PASSWORD="mysql660"
DB_HOST="127.0.0.1"
DB_PORT="3306"
DB_NAME="opentalent"
DB_TEST_NAME="opentalent_test"
MARIADB_CONTAINER="mariaDb"

# Fonction pour réinitialiser la base de données de test
reset_test_database() {
    echo "Dropping test database if it exists..."
    docker exec $MARIADB_CONTAINER mysql --user=$DB_USER --password=$DB_PASSWORD --host=$DB_HOST --port=$DB_PORT -e "DROP DATABASE IF EXISTS $DB_TEST_NAME;"

    echo "Dumping schema from the main database..."
    docker exec $MARIADB_CONTAINER mysqldump --user=$DB_USER --password=$DB_PASSWORD --host=$DB_HOST --port=$DB_PORT --default-character-set=utf8 --single-transaction=TRUE --no-data --skip-triggers "$DB_NAME" | sed 's/ AUTO_INCREMENT=[0-9]*//g' > opentalent_test.sql

    echo "Creating test database..."
    docker exec $MARIADB_CONTAINER mysql --user=$DB_USER --password=$DB_PASSWORD --host=$DB_HOST --port=$DB_PORT -e "CREATE DATABASE $DB_TEST_NAME;"

    echo "Importing schema into the test database..."
    docker exec -i $MARIADB_CONTAINER mysql --user=$DB_USER --password=$DB_PASSWORD --host=$DB_HOST --port=$DB_PORT -D $DB_TEST_NAME < opentalent_test.sql

    echo "Database setup completed."
}

# Réinitialiser la base de données de test
reset_test_database

total_tests=0
passed_tests=0
failed_tests=0

for test_file in $(find tests/Application -name "*Test.php"); do
    echo "Running test: $test_file"
    php bin/phpunit $test_file
    result=$?

    total_tests=$((total_tests + 1))
    if [ $result -ne 0 ]; then
        echo "Test failed: $test_file"
        failed_tests=$((failed_tests + 1))
    else
        passed_tests=$((passed_tests + 1))
    fi
done

echo "===================================="
echo "Test Summary:"
echo "Total tests run: $total_tests"
echo "Tests passed: $passed_tests"
echo "Tests failed: $failed_tests"
echo "===================================="

if [ $failed_tests -ne 0 ]; then
    exit 1
else
    exit 0
fi
