<?php

namespace App\Tests\ClinicService;

use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceSection;
use App\Doctor\Entity\Doctor;
use App\Tests\ApiTestCase;

/**
 * GET /api/v1/service-items resolves the caller's working context. A user with
 * neither a doctor profile nor a clinic (admin, secretary, representation, plain
 * patient) resolves to EntityContext::unknown(), whose id is null — which used
 * to reach ServiceItemRepository::findByEntity(int $entityId) and fatal with a
 * 500. It must be a 403 instead.
 */
class ServiceItemsUnresolvedContextTest extends ApiTestCase
{
    public function testUserWithoutDoctorOrClinicGetsForbiddenNotServerError(): void
    {
        foreach ([['ROLE_ADMIN'], ['ROLE_SECRETARY'], ['ROLE_REPRESENTATION'], ['ROLE_USER']] as $roles) {
            $user = $this->createUser($roles);

            $this->authJson('GET', '/api/v1/service-items', $user);

            $this->assertSame(
                403,
                $this->responseCode(),
                sprintf('roles %s should be forbidden, not a server error', implode(',', $roles)),
            );
        }
    }

    public function testDoctorStillGetsTheirOwnItems(): void
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر تست محیط');
        $this->em->persist($doctor);
        $this->em->flush();

        $section = new ServiceSection('doctor', $doctor->getId(), 'تزریقات');
        $item    = new ServiceItem($section, 'سرم ۵۰۰cc');
        $this->em->persist($section);
        $this->em->persist($item);
        $this->em->flush();

        $body = $this->authJson('GET', '/api/v1/service-items', $owner);

        $this->assertSame(200, $this->responseCode());
        $this->assertTrue($body['success']);
        $this->assertContains('سرم ۵۰۰cc', array_column($body['data'], 'name'));
    }
}
