<?php

namespace App\Tests\Appointment;

use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorAddress;
use App\Resource\Entity\ClinicResource;
use App\Resource\Entity\ResourceType;
use App\Tests\ApiTestCase;

/**
 * حالت نوبت‌دهی منبع‌محور بدون منبع فعال، هیچ وقتی نمی‌سازد — و چون انتخابِ حالت
 * برگشت‌ناپذیر است، محیط برای همیشه قفل می‌شد. پس شرطش پیش از ثبت سنجیده می‌شود.
 */
class ResourceModeReadinessTest extends ApiTestCase
{
    /** @return array{0: \App\Auth\Entity\User, 1: Doctor} */
    private function makeDoctor(): array
    {
        $owner  = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر منبع');
        $this->em->persist($doctor);
        $this->em->flush();

        return [$owner, $doctor];
    }

    private function giveResource(Doctor $doctor): void
    {
        $address = DoctorAddress::forDoctor($doctor);
        $address->setName('مطب');
        $this->em->persist($address);
        $this->em->flush();

        $type = new ResourceType('doctor', (int) $doctor->getId(), 'room', 'اتاق');
        $this->em->persist($type);
        $this->em->flush();

        $resource = new ClinicResource($address, $type, 'اتاق ۱');
        $this->em->persist($resource);
        $this->em->flush();
    }

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

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

        self::assertSame(422, $this->responseCode(), json_encode($body, JSON_UNESCAPED_UNICODE));
        self::assertStringContainsString('حداقل یک منبع فعال', json_encode($body, JSON_UNESCAPED_UNICODE));
    }

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

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

        self::assertSame(201, $this->responseCode(), json_encode($body, JSON_UNESCAPED_UNICODE));
    }

    /** حالت اسلاتی هیچ شرط منبعی ندارد؛ نگهبان نباید مسیر موجود را بشکند. */
    public function testSlotModeStillNeedsNothing(): void
    {
        [$owner, $doctor] = $this->makeDoctor();

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

        self::assertSame(201, $this->responseCode());
    }
}
