<?php

namespace App\Tests\Patient;

use App\Doctor\Entity\Doctor;
use App\Patient\Entity\PatientRecord;
use App\Tests\ApiTestCase;

/**
 * Patient medical records: CRUD + tenant ownership scoping.
 */
class PatientMedicalRecordTest extends ApiTestCase
{
    /** @return array{0: \App\Auth\Entity\User, 1: PatientRecord} */
    private function recordFor(): array
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر');
        $this->em->persist($doctor);
        $this->em->flush();

        $patient = $this->createUser(['ROLE_USER']);
        $record  = new PatientRecord('doctor', $doctor->getId(), $patient, 'doctor', $doctor->getId());
        $this->em->persist($record);
        $this->em->flush();

        return [$owner, $record];
    }

    public function testCrud(): void
    {
        [$owner, $record] = $this->recordFor();

        $created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/medical-record', $owner, [
            'title' => 'معاینه اولیه', 'body' => 'فشار خون طبیعی', 'recorded_at' => 1_700_000_000,
        ]);
        self::assertSame(201, $this->responseCode());
        self::assertSame('معاینه اولیه', $created['data']['title']);
        $mUuid = $created['data']['uuid'];

        $list = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/medical-records', $owner);
        self::assertCount(1, $list['data']);

        $this->authJson('PATCH', '/api/v1/patient/medical-record/' . $mUuid, $owner, ['title' => 'معاینه دوم']);
        self::assertSame(200, $this->responseCode());

        $this->authJson('DELETE', '/api/v1/patient/medical-record/' . $mUuid, $owner);
        self::assertSame(200, $this->responseCode());

        $after = $this->authJson('GET', '/api/v1/patient/' . $record->getUuid() . '/medical-records', $owner);
        self::assertCount(0, $after['data']);
    }

    public function testRequiresTitle(): void
    {
        [$owner, $record] = $this->recordFor();
        $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/medical-record', $owner, ['title' => '']);
        self::assertSame(422, $this->responseCode());
    }

    public function testOwnershipScoped(): void
    {
        [$owner, $record] = $this->recordFor();
        $created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/medical-record', $owner, ['title' => 'x']);
        $mUuid   = $created['data']['uuid'];

        [$other] = $this->recordFor();
        $this->authJson('DELETE', '/api/v1/patient/medical-record/' . $mUuid, $other);
        self::assertSame(404, $this->responseCode());
    }
}
