<?php

namespace Tests\Feature;

use App\Services\AdOps\ApiClient;
use CodeIgniter\Test\CIUnitTestCase;

/**
 * The importer writes through ApiClient's X-API-ADVID header, while every grid
 * that shows the result reads with auth_master_adv_id(). When those two
 * disagree, a linked sub-user's import lands under an id no grid queries: the
 * row is written correctly but is invisible, and re-uploading the same file
 * still trips the API's duplicate precheck, which does match on that id.
 *
 * Pinned here because it is the header value, not a query, that carries the
 * scope — nothing in the unit suite can see it.
 *
 * Fixtures are the linked accounts MasterScopingTest uses (admin 17307 and
 * viewer 17306 under master 17237). Runs against the dev Admin DB.
 */
final class ImportExportScopingTest extends CIUnitTestCase
{
    private const MASTER     = 17237;
    private const ADMIN_SUB  = 17307;
    private const VIEWER_SUB = 17306;
    private const OTHER      = 15196;

    protected function tearDown(): void
    {
        session()->destroy();
        parent::tearDown();
    }

    /** The advertiser id ApiClient would send for a given logged-in session. */
    private function advIdSentFor(int $sessionAdvId): int
    {
        session()->set([
            'logged_in' => 1,
            'adv_id'    => $sessionAdvId,
            'user_id'   => $sessionAdvId,
            'role'      => 'admin',
        ]);

        return $this->advIdOf(new ApiClient());
    }

    private function advIdOf(ApiClient $client): int
    {
        $prop = new \ReflectionProperty(ApiClient::class, 'advId');
        $prop->setAccessible(true);

        return (int) $prop->getValue($client);
    }

    public function testASubUserImportsUnderTheMasterAdvertiser(): void
    {
        // The regression: this used to be 17307, so the row went somewhere the
        // creatives grid never looks.
        $this->assertSame(self::MASTER, $this->advIdSentFor(self::ADMIN_SUB));
    }

    public function testAViewerSubUserResolvesToTheSameMaster(): void
    {
        $this->assertSame(self::MASTER, $this->advIdSentFor(self::VIEWER_SUB));
    }

    public function testAMasterAccountImportsUnderItsOwnId(): void
    {
        $this->assertSame(self::MASTER, $this->advIdSentFor(self::MASTER));
    }

    public function testAnUnrelatedAccountIsNotRemapped(): void
    {
        // Guards against the fix over-reaching into a cross-tenant remap.
        $this->assertSame(self::OTHER, $this->advIdSentFor(self::OTHER));
    }

    public function testAnExplicitAdvertiserIdStillWins(): void
    {
        session()->set(['logged_in' => 1, 'adv_id' => self::ADMIN_SUB]);

        $this->assertSame(4242, $this->advIdOf(new ApiClient(4242)));
    }
}
