<?php

namespace App\Tests\Appointment;

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

/**
 * نوع نوبت‌دهی (booking_mode) پس از اولین ثبت غیرقابل‌تغییر است.
 */
class BookingModeImmutableTest extends ApiTestCase
{
    private function makeDoctor(): array
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر قفل');
        $this->em->persist($doctor);
        $this->em->flush();
        return [$owner, $doctor];
    }

    public function testFirstSaveCommitsAndSecondSaveKeepsSameMode(): void
    {
        [$owner, $doctor] = $this->makeDoctor();

        $this->authJson('POST', '/api/v1/appointment-settings/weekly-schedule', $owner, [
            'doctor_uuid' => $doctor->getUuid(),
            'schedule'    => [],
            'meta'        => ['booking_mode' => 'slot'],
        ]);
        $this->assertSame(201, $this->responseCode());

        // همان mode دوباره → مجاز
        $this->authJson('PATCH', '/api/v1/appointment-settings/weekly-schedule/' . $doctor->getUuid(), $owner, [
            'meta' => ['booking_mode' => 'slot'],
        ]);
        $this->assertSame(200, $this->responseCode());
    }

    public function testCannotChangeModeAfterCommit(): void
    {
        [$owner, $doctor] = $this->makeDoctor();

        $this->authJson('POST', '/api/v1/appointment-settings/weekly-schedule', $owner, [
            'doctor_uuid' => $doctor->getUuid(),
            'schedule'    => [],
            'meta'        => ['booking_mode' => 'slot'],
        ]);
        $this->assertSame(201, $this->responseCode());

        // تلاش برای تغییر به سرویس → 422 قفل
        $res = $this->authJson('PATCH', '/api/v1/appointment-settings/weekly-schedule/' . $doctor->getUuid(), $owner, [
            'meta' => ['booking_mode' => 'service'],
        ]);
        $this->assertSame(422, $this->responseCode());
        $this->assertStringContainsString('قابل تغییر نیست', json_encode($res, JSON_UNESCAPED_UNICODE));
    }
}
