<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/feca_mailshots_plugin/src/autoload.php';

use FecaMailshots\Admin\DataSourcesAdminPage;
use FecaMailshots\Admin\SetupAdminPage;
use FecaMailshots\WordPress\FixtureWordPressFacade;

$wp = new FixtureWordPressFacade();

/** @param callable():void $fn */
$capture = static function (callable $fn): string {
    ob_start();
    try {
        $fn();
        return (string) ob_get_clean();
    } catch (\Throwable $e) {
        ob_end_clean();
        throw $e;
    }
};

$assertTrue = static function (bool $condition, string $message): void {
    if (!$condition) {
        fwrite(STDERR, "Assertion failed: {$message}\n");
        exit(1);
    }
};

$assertContains = static function (string $needle, string $haystack, string $label): void {
    if (strpos($haystack, $needle) === false) {
        fwrite(STDERR, "Missing expected text in {$label}: {$needle}\n");
        exit(1);
    }
};

$setup = new SetupAdminPage($wp);
$dataSources = new DataSourcesAdminPage(
    static function (): never {
        throw new RuntimeException('Data source service should not be resolved in this test.');
    },
    $wp
);

// Editor policy: operational features allowed via edit_pages, setup denied.
$wp->setAllowedCapabilities(['edit_pages']);
$assertTrue($dataSources->restCanRead() === true, 'Editor must be able to read data source REST endpoints.');
$assertTrue($dataSources->restCanManage() === true, 'Editor must be able to manage data source REST endpoints.');
$setupDeniedHtml = $capture(static function () use ($setup): void {
    $setup->render();
});
$assertContains('Permission denied', $setupDeniedHtml, 'Setup (editor)');

// Administrator policy: setup/settings allowed via manage_options.
$wp->setAllowedCapabilities(['manage_options']);
$setupAdminHtml = $capture(static function () use ($setup): void {
    $setup->render();
});
$assertContains('FECA Mailshots Setup', $setupAdminHtml, 'Setup (admin)');

// No-capability baseline: operational data-source endpoints denied.
$wp->setAllowedCapabilities([]);
$assertTrue($dataSources->restCanRead() === false, 'User without edit_pages must not read data source REST endpoints.');
$assertTrue($dataSources->restCanManage() === false, 'User without edit_pages must not manage data source REST endpoints.');

echo "Access control policy integration test passed\n";
