<?php

namespace App\Tests\Clinic;

use App\Clinic\Entity\Clinic;
use App\Tests\ApiTestCase;

/**
 * POST /api/v1/clinic is a self-service signup: any authenticated user may
 * register their own clinic. Two invariants it used to break —
 *  · an empty body created a nameless clinic that no list can identify;
 *  · a user could create unlimited clinics, while ClinicRepository::findByUser()
 *    (which resolves their working context) is a findOneBy, so every clinic past
 *    the first was unreachable data.
 */
class CreateClinicValidationTest extends ApiTestCase
{
    public function testEmptyBodyIsRejected(): void
    {
        $user = $this->createUser(['ROLE_USER']);

        $body = $this->authJson('POST', '/api/v1/clinic', $user);

        $this->assertSame(422, $this->responseCode());
        $this->assertFalse($body['success']);
        $this->assertSame('name', $body['errors'][0]['field'] ?? null);
    }

    public function testBlankNameIsRejected(): void
    {
        $user = $this->createUser(['ROLE_USER']);

        $this->authJson('POST', '/api/v1/clinic', $user, ['name' => '   ']);

        $this->assertSame(422, $this->responseCode());
    }

    public function testNamedClinicIsCreatedAndGrantsClinicRole(): void
    {
        $user = $this->createUser(['ROLE_USER']);

        $this->authJson('POST', '/api/v1/clinic', $user, ['name' => 'کلینیک شفا']);

        $this->assertSame(201, $this->responseCode());

        $this->em->refresh($user);
        $this->assertContains('ROLE_CLINIC', $user->getRoles());

        $clinic = $this->em->getRepository(Clinic::class)->findOneBy(['user' => $user]);
        $this->assertNotNull($clinic);
        $this->assertSame('کلینیک شفا', $clinic->getName());
    }

    public function testSecondClinicForTheSameUserIsRejected(): void
    {
        $user = $this->createUser(['ROLE_USER']);

        $this->authJson('POST', '/api/v1/clinic', $user, ['name' => 'کلینیک اول']);
        $this->assertSame(201, $this->responseCode());

        $body = $this->authJson('POST', '/api/v1/clinic', $user, ['name' => 'کلینیک دوم']);

        $this->assertSame(409, $this->responseCode());
        $this->assertSame('ERR_CONFLICT_001', $body['errors'][0]['code'] ?? null);

        $count = $this->em->getRepository(Clinic::class)->count(['user' => $user]);
        $this->assertSame(1, $count, 'a user must never end up owning more than one clinic');
    }
}
