<?php

namespace App\Tests\Appointment;

use App\Appointment\Entity\WeeklySchedule;
use App\Auth\Entity\User;
use App\Doctor\Entity\Doctor;
use App\Tests\ApiTestCase;

/**
 * Regression: GET weekly-schedule must enforce ownership (IDOR fix).
 * Before the fix any authenticated user could read any doctor's schedule.
 */
class ScheduleOwnershipTest extends ApiTestCase
{
    private function makeDoctorWithSchedule(): array
    {
        $owner = $this->createUser(['ROLE_DOCTOR']);
        $doctor = new Doctor($owner, 'دکتر تست');
        $this->em->persist($doctor);
        $schedule = new WeeklySchedule($doctor, ['sat' => []]);
        $this->em->persist($schedule);
        $this->em->flush();

        return [$owner, $doctor];
    }

    public function testOwnerCanReadOwnSchedule(): void
    {
        [$owner, $doctor] = $this->makeDoctorWithSchedule();
        $this->authJson('GET', '/api/v1/appointment-settings/weekly-schedule/' . $doctor->getUuid(), $owner);
        $this->assertSame(200, $this->responseCode());
    }

    public function testOtherUserIsForbidden(): void
    {
        [, $doctor] = $this->makeDoctorWithSchedule();
        $attacker = $this->createUser(['ROLE_DOCTOR']);
        $this->authJson('GET', '/api/v1/appointment-settings/weekly-schedule/' . $doctor->getUuid(), $attacker);
        $this->assertSame(403, $this->responseCode());
    }

    public function testAdminCanRead(): void
    {
        [, $doctor] = $this->makeDoctorWithSchedule();
        $admin = $this->createUser(['ROLE_ADMIN']);
        $this->authJson('GET', '/api/v1/appointment-settings/weekly-schedule/' . $doctor->getUuid(), $admin);
        $this->assertSame(200, $this->responseCode());
    }
}
