<?php

namespace App\Tests\Patient;

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

/**
 * Patient messages: create, list, delete + tenant ownership scoping.
 */
class PatientMessageTest 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 testCreateListDelete(): void
    {
        [$owner, $record] = $this->recordFor();

        $created = $this->authJson('POST', '/api/v1/patient/' . $record->getUuid() . '/message', $owner, [
            'body' => 'یادآوری نوبت فردا', 'channel' => 'sms',
        ]);
        self::assertSame(201, $this->responseCode());
        self::assertSame('یادآوری نوبت فردا', $created['data']['body']);
        self::assertSame('sms', $created['data']['channel']);
        $mUuid = $created['data']['uuid'];

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

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

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

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

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

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