<?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/Permission.php';
require_once BASE_PATH . '/app/helpers/Authorization.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.');
}

$permission = new Permission();
$allAllowed = ['customer' => [], 'owner' => []];
foreach (Permission::definitions() as $key => $_definition) {
    foreach (array_keys($allAllowed) as $role) {
        if (str_starts_with($key, $role . '.')) {
            $allAllowed[$role][] = $key;
        }
    }
}

if (!$permission->can('customer', 'customer.booking.create')
    || !$permission->can('owner', 'owner.service.manage')
    || $permission->can('customer', 'owner.service.manage')) {
    throw new RuntimeException('Default role permission matrix is incorrect.');
}

$withoutBookingCreation = $allAllowed;
$withoutBookingCreation['customer'] = array_values(array_filter(
    $withoutBookingCreation['customer'],
    fn (string $key): bool => $key !== 'customer.booking.create'
));

$permission->saveMatrix($withoutBookingCreation);
if ($permission->can('customer', 'customer.booking.create')) {
    throw new RuntimeException('Disabled permission still allowed customer access.');
}
if (!$permission->can('owner', 'owner.service.manage')) {
    throw new RuntimeException('Owner permission changed unexpectedly.');
}

$routeChecks = [
    'customer/booking/store' => 'customer.booking.create',
    'owner/service/edit' => 'owner.service.manage',
    'owner/service-category/update' => 'owner.service_category.manage',
    'owner/booking/status' => 'owner.booking.manage',
    'owner/settings/update' => 'owner.settings.manage'
];
foreach ($routeChecks as $route => $expectedPermission) {
    if (Authorization::permissionForRoute($route) !== $expectedPermission) {
        throw new RuntimeException('Incorrect permission mapping for ' . $route);
    }
}

$permission->saveMatrix($allAllowed);
if (!$permission->can('customer', 'customer.booking.create')) {
    throw new RuntimeException('Permission matrix was not restored.');
}

echo "PERMISSIONS E2E PASS: matrix persistence, menu/backend route keys, role isolation\n";
