<?php

declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

$testDatabase = (string) getenv('PET_SPA_TEST_DB');
if (!preg_match('/^pet_shop_e2e_[a-z0-9_]+$/', $testDatabase)) {
    throw new RuntimeException('Refusing to run: use an isolated pet_shop_e2e_* database.');
}

require_once BASE_PATH . '/config/database.php';
require_once BASE_PATH . '/app/models/SpaActivityLog.php';

$database = new Database();
$pdo = $database->connect();
if ($database->databaseName() !== $testDatabase
    || $pdo->query('SELECT DATABASE()')->fetchColumn() !== $testDatabase
    || $testDatabase === 'pet_shop') {
    throw new RuntimeException('Refusing destructive E2E test against the main database.');
}

$pdo->prepare(
    'INSERT INTO users (full_name, phone, email, password_hash, role)
     VALUES (?, ?, ?, ?, "owner")'
)->execute(['E2E Audit Owner', '08' . random_int(10000000, 99999999), 'audit-' . bin2hex(random_bytes(3)) . '@example.test', 'x']);
$ownerId = (int) $pdo->lastInsertId();
$logger = new SpaActivityLog();
$logger->record($ownerId, 'owner.service.create', 'service', 123, ['is_active' => 1]);
$count = (int) $pdo->query("SELECT COUNT(*) FROM activity_logs WHERE action = 'owner.service.create'")->fetchColumn();
if ($count !== 1) {
    throw new RuntimeException('Enabled activity log was not recorded.');
}

$pdo->query("UPDATE system_settings SET setting_value = '0' WHERE setting_key = 'activity_logging_enabled'");
$logger->record($ownerId, 'owner.service.update', 'service', 123);
$disabledCount = (int) $pdo->query("SELECT COUNT(*) FROM activity_logs WHERE action = 'owner.service.update'")->fetchColumn();
$pdo->query("UPDATE system_settings SET setting_value = '1' WHERE setting_key = 'activity_logging_enabled'");
if ($disabledCount !== 0) {
    throw new RuntimeException('Disabled activity logging still wrote an event.');
}

echo "SPA ACTIVITY LOG E2E PASS: enabled audit write and disabled policy\n";
