<?php

namespace TbiBank\FusionPay\Test\Unit\Observer;

use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Event;
use Magento\Framework\Event\Observer;
use PHPUnit\Framework\TestCase;
use TbiBank\FusionPay\Observer\CleanPageCacheAfterSettingsSave;

/**
 * Behaviour under test: TbiBank\FusionPay\Observer\CleanPageCacheAfterSettingsSave (CKT-3933)
 *
 * Magento_PageCache only flags full_page as invalidated on controller postdispatch of a config
 * save, so the storefront kept serving pages rendered with the previous FusionPay settings.
 *
 * Given the admin config save controller has finished
 * When  the saved section is the Fusion Pay RO settings section
 * Then  full_page is cleaned (which also clears its invalidated flag); other sections are left alone.
 */
class CleanPageCacheAfterSettingsSaveTest extends TestCase
{
    private function postdispatchFor(string $section): Observer
    {
        $request = $this->createMock(RequestInterface::class);
        $request->method('getParam')->willReturnCallback(
            fn ($key) => $key === 'section' ? $section : null
        );

        return (new Observer())->setEvent((new Event())->setRequest($request));
    }

    public function testFusionPaySettingsSaveCleansPageCache(): void
    {
        $cacheTypeList = $this->createMock(TypeListInterface::class);
        $cacheTypeList->expects($this->once())->method('cleanType')->with('full_page');

        (new CleanPageCacheAfterSettingsSave($cacheTypeList))->execute($this->postdispatchFor('tbi_settings'));
    }

    public function testOtherSectionSaveLeavesPageCacheToMagento(): void
    {
        $cacheTypeList = $this->createMock(TypeListInterface::class);
        $cacheTypeList->expects($this->never())->method('cleanType');

        (new CleanPageCacheAfterSettingsSave($cacheTypeList))->execute($this->postdispatchFor('payment'));
    }

    public function testObserverRunsAfterTheAdminConfigSaveController(): void
    {
        $xml = new \DOMDocument();
        $xml->load(dirname(__DIR__, 3) . '/etc/adminhtml/events.xml');
        $xpath = new \DOMXPath($xml);

        $observers = $xpath->query(
            "//event[@name='controller_action_postdispatch_adminhtml_system_config_save']"
            . "/observer[@instance='TbiBank\\FusionPay\\Observer\\CleanPageCacheAfterSettingsSave']"
        );

        $this->assertSame(1, $observers->length);
    }
}
