<?php

namespace Tests\Feature;

use CodeIgniter\Test\CIUnitTestCase;
use Config\Services;

/**
 * Single-advertiser tool gating (qa-authorization-fixes).
 *
 * Preview Tool (15618) must be visible/reachable only for its allowlisted
 * account (resolving the master so sub-users pass) or a mngt-portal user.
 * auth_can_preview_tool() backs BOTH the sidebar nav visibility and the
 * in-controller 404, so testing the helper covers both surfaces.
 */
final class SpecialAdvGatingTest extends CIUnitTestCase
{
    private const PREVIEW    = 15618;
    private const AMAZON     = 20378;
    private const VIEWER_SUB = 17306; // sub-user of State Farm master 17237

    protected function setUp(): void
    {
        parent::setUp();
        helper('auth');
    }

    private function loginAdvertiser(int $advId): void
    {
        $this->mockSession();
        Services::session()->set(['logged_in' => 1, 'adv_id' => $advId, 'user_id' => $advId, 'role' => 'admin']);
    }

    private function loginMngt(int $advId): void
    {
        $this->mockSession();
        Services::session()->set([
            'logged_in' => 1, 'adv_id' => $advId, 'user_id' => 1,
            'mngtuser' => 'qabot', 'is_superuser' => 1,
        ]);
    }

    public function testPreviewAdvertiserSeesPreview(): void
    {
        $this->loginAdvertiser(self::PREVIEW);
        $this->assertTrue(auth_can_preview_tool());
    }

    public function testAmazonDirectSeesNoPreview(): void
    {
        $this->loginAdvertiser(self::AMAZON);
        $this->assertFalse(auth_can_preview_tool());
    }

    public function testUnrelatedSubUserSeesNoPreview(): void
    {
        $this->loginAdvertiser(self::VIEWER_SUB);
        $this->assertFalse(auth_can_preview_tool());
    }

    public function testMngtUserPassesPreview(): void
    {
        $this->loginMngt(self::AMAZON);
        $this->assertTrue(auth_can_preview_tool());
    }
}
