<?php

namespace App\Tests\Representation;

use App\Representation\Entity\Representation;
use App\Tests\ApiTestCase;

/**
 * commission_percent / active are admin-only on PATCH representation, and the
 * commission value is range-checked. Guards against a representative raising
 * their own commission or self-activating.
 */
class RepresentationCommissionTest extends ApiTestCase
{
    private function makeRep(): array
    {
        $owner = $this->createUser(['ROLE_USER', 'ROLE_REPRESENTATION']);
        $rep = new Representation($owner, 'نماینده تست');
        $rep->setCommissionPercent('10');
        $this->em->persist($rep);
        $this->em->flush();

        return [$owner, $rep];
    }

    public function testOwnerCannotChangeOwnCommission(): void
    {
        [$owner, $rep] = $this->makeRep();
        $this->authJson('PATCH', '/api/v1/representation/' . $rep->getUuid(), $owner, [
            'commission_percent' => 90,
        ]);
        $this->assertSame(403, $this->responseCode());

        $this->em->clear();
        $fresh = $this->em->getRepository(Representation::class)->find($rep->getId());
        $this->assertSame(10.0, (float) $fresh->getCommissionPercent());
    }

    public function testOwnerCannotSelfActivate(): void
    {
        [$owner, $rep] = $this->makeRep();
        $this->authJson('PATCH', '/api/v1/representation/' . $rep->getUuid(), $owner, [
            'active' => true,
        ]);
        $this->assertSame(403, $this->responseCode());
    }

    public function testAdminCanChangeCommission(): void
    {
        [, $rep] = $this->makeRep();
        $admin = $this->createUser(['ROLE_ADMIN']);
        $this->authJson('PATCH', '/api/v1/representation/' . $rep->getUuid(), $admin, [
            'commission_percent' => 25,
        ]);
        $this->assertSame(200, $this->responseCode());
    }

    public function testAdminRejectedOnOutOfRangeCommission(): void
    {
        [, $rep] = $this->makeRep();
        $admin = $this->createUser(['ROLE_ADMIN']);
        $this->authJson('PATCH', '/api/v1/representation/' . $rep->getUuid(), $admin, [
            'commission_percent' => 150,
        ]);
        $this->assertSame(422, $this->responseCode());
    }

    public function testOwnerCanStillEditOwnName(): void
    {
        [$owner, $rep] = $this->makeRep();
        $this->authJson('PATCH', '/api/v1/representation/' . $rep->getUuid(), $owner, [
            'full_name' => 'نام جدید',
        ]);
        $this->assertSame(200, $this->responseCode());
    }
}
