<?php

namespace App\ClinicService\Controller;

use App\Auth\Entity\User;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceItemAuditLog;
use App\ClinicService\Entity\ServiceSection;
use App\Insurance\Entity\TenantServiceCoverage;
use App\Insurance\Enum\ServiceCategory;
use App\ClinicService\Entity\Tariff;
use App\Clinic\Security\ClinicDoctorAccessChecker;
use App\Secretary\Security\SecretaryAccessChecker;
use Doctrine\ORM\EntityManagerInterface;
use App\ClinicService\Repository\ServiceItemAuditLogRepository;
use App\ClinicService\Repository\ServiceItemRepository;
use App\ClinicService\Repository\ServiceSectionRepository;
use App\ClinicService\Repository\TariffRepository;
use App\ClinicService\Service\ServiceItemAuditService;
use App\ClinicService\Service\TariffService;
use App\Inventory\Repository\InventoryItemRepository;
use App\Inventory\Repository\InventoryPackageRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Context\EntityContextResolver;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
use App\Staff\Repository\ClinicStaffRepository;
use App\Subscription\Service\SubscriptionService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use OpenApi\Attributes as OA;

#[OA\Tag(name: 'Clinic Services')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class ClinicServiceController extends BaseController
{
    public function __construct(
        private readonly ServiceSectionRepository $sectionRepo,
        private readonly ServiceItemRepository    $itemRepo,
        private readonly ClinicStaffRepository    $staffRepo,
        private readonly SubscriptionService      $subscriptionService,
        private readonly TariffRepository         $tariffRepo,
        private readonly TariffService            $tariffService,
        private readonly InventoryPackageRepository $packageRepo,
        private readonly InventoryItemRepository $inventoryItemRepo,
        private readonly ServiceItemAuditService $auditService,
        private readonly ServiceItemAuditLogRepository $auditLogRepo,
        private readonly EntityManagerInterface   $em,
        private readonly EntityContextResolver    $contextResolver,
        private readonly RequestStack             $requestStack,
        private readonly SecretaryAccessChecker   $secretaryAccess,
        private readonly ClinicDoctorAccessChecker $clinicDoctorAccess,
    ) {}

    /** گِیتِ ترکیبی: منشی + پزشکِ عضوِ کلینیک (هرکدام فقط نقشِ خودش را محدود می‌کند). */
    private function denyServices(User $user, string $action): void
    {
        $this->secretaryAccess->denyUnlessGranted($user, 'services', $action);
        $this->clinicDoctorAccess->denyUnlessGranted($user, 'services', $action);
    }

    /**
     * uuid و عنوان پکیج کالای هر سرویس را به آرایه‌ی خروجی اضافه می‌کند. پکیج‌ها با یک
     * کوئری واکشی می‌شوند تا فهرست سرویس‌ها به N+1 نیفتد.
     *
     * @param  ServiceItem[] $items
     * @return array<int, array<string, mixed>>
     */
    private function serializeItems(array $items): array
    {
        $packages = $this->packageRepo->findMapByIds(
            array_map(fn(ServiceItem $i) => $i->getInventoryPackageId(), $items)
        );

        return array_map(function (ServiceItem $i) use ($packages) {
            $row     = $i->toArray();
            $package = $packages[$i->getInventoryPackageId()] ?? null;
            $row['inventory_package_uuid']  = $package?->getUuid();
            $row['inventory_package_title'] = $package?->getTitle();

            return $row;
        }, $items);
    }

    /**
     * `inventory_package_uuid` را به id داخلی تبدیل و روی سرویس ست می‌کند.
     * مقدار null یعنی قطع اتصال. خطای دسترسی/نبود پکیج را برمی‌گرداند.
     */
    private function applyInventoryPackage(ServiceItem $item, array $data, string $entityType, ?int $entityId): ?JsonResponse
    {
        if (!array_key_exists('inventory_package_uuid', $data)) {
            return null;
        }

        $uuid = $data['inventory_package_uuid'];
        if ($uuid === null || $uuid === '') {
            $item->setInventoryPackageId(null);
            return null;
        }

        $package = $this->packageRepo->findByUuid((string) $uuid);
        if ($package === null || $package->getEntityType() !== $entityType || $package->getEntityId() !== $entityId) {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پکیج کالا یافت نشد', 422, 'inventory_package_uuid');
        }

        $item->setInventoryPackageId($package->getId());

        return null;
    }

    /** نوع خدمت (سرپایی/بستری) را ست می‌کند؛ مقدار نامعتبر ۴۲۲ می‌دهد. */
    private function applyServiceCategory(ServiceItem $item, array $data): ?JsonResponse
    {
        if (!array_key_exists('service_category', $data)) {
            return null;
        }

        $category = ServiceCategory::tryFromValue(
            $data['service_category'] !== null ? (string) $data['service_category'] : null
        );
        if ($category === null) {
            return $this->error(
                ErrorCodes::ERR_VALIDATION_001,
                'نوع خدمت نامعتبر است: ' . implode('، ', ServiceCategory::values()),
                422,
                'service_category',
            );
        }

        $item->setServiceCategory($category);

        return null;
    }

    /**
     * `consumables: [{item_uuid, amount}]` را روی خدمت می‌نشاند. آرایه‌ی خالی یعنی حذف
     * همه‌ی اقلام. هر قلم باید متعلق به همان مطب/کلینیک باشد.
     */
    private function applyConsumables(ServiceItem $item, array $data, string $entityType, ?int $entityId): ?JsonResponse
    {
        if (!array_key_exists('consumables', $data)) {
            return null;
        }

        $lines = [];
        foreach ((array) ($data['consumables'] ?? []) as $raw) {
            $uuid = is_array($raw) ? ($raw['item_uuid'] ?? null) : null;
            if ($uuid === null || $uuid === '') {
                continue;
            }

            $inventoryItem = $this->inventoryItemRepo->findByUuid((string) $uuid);
            if ($inventoryItem === null
                || $inventoryItem->getEntityType() !== $entityType
                || $inventoryItem->getEntityId() !== $entityId
            ) {
                return $this->error(ErrorCodes::ERR_VALIDATION_001, 'کالای انتخاب‌شده یافت نشد', 422, 'consumables');
            }

            $lines[] = ['item' => $inventoryItem, 'amount' => max(1, (int) ($raw['amount'] ?? 1))];
        }

        $item->replaceConsumables($lines);

        return null;
    }

    // ── Service categories (سرپایی/بستری) ────────────────────────────────────

    /**
     * تنها منبع لیست نوع خدمت برای فرانت (فرم خدمت و تنظیمات پوشش بیمه)؛
     * افزودن نوع تازه فقط یک case در ServiceCategory است و اینجا خودکار ظاهر می‌شود.
     */
    #[Route('/api/v1/service-categories', methods: ['GET'])]
    public function listServiceCategories(): JsonResponse
    {
        return $this->success([
            'data' => array_map(
                static fn(ServiceCategory $c) => ['key' => $c->value, 'label' => $c->label()],
                ServiceCategory::cases(),
            ),
        ]);
    }

    // ── Service Sections ─────────────────────────────────────────────────────

    #[Route('/api/v1/service-sections', methods: ['GET'])]
    public function listSections(#[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'view');
        [$entityType, $entityId] = $this->resolveEntity($user);
        $this->assertServicesGate($entityType, $entityId);

        $sectionEntities = $this->sectionRepo->findByEntity($entityType, $entityId);
        $counts          = $this->itemRepo->countBySections($sectionEntities);

        $sections = array_map(
            fn(ServiceSection $s) => $s->toArray($counts[$s->getUuid()] ?? 0),
            $sectionEntities
        );

        return $this->success($sections);
    }

    #[Route('/api/v1/service-section', methods: ['POST'])]
    public function createSection(Request $request, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'create');
        [$entityType, $entityId] = $this->resolveEntity($user);
        $this->assertServicesGate($entityType, $entityId);

        $data = json_decode($request->getContent(), true) ?? [];
        $name = trim($data['name'] ?? '');

        if ($name === '') {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'name الزامی است', 422);
        }

        $section = new ServiceSection($entityType, $entityId, $name);
        $this->sectionRepo->save($section);

        return $this->success($section->toArray(), 201);
    }

    #[Route('/api/v1/service-section/{uuid}', methods: ['PATCH'])]
    public function updateSection(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'update');
        [$entityType, $entityId] = $this->resolveEntity($user);
        $this->assertServicesGate($entityType, $entityId);

        $section = $this->sectionRepo->findByUuid($uuid);
        if ($section === null || !$this->ownsSection($section, $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        $data = json_decode($request->getContent(), true) ?? [];
        if (isset($data['name']) && trim($data['name']) !== '') {
            $section->setName(trim($data['name']));
        }
        if (isset($data['active'])) {
            $section->setActive((bool) $data['active']);
        }

        $this->sectionRepo->save($section);

        return $this->success($section->toArray());
    }

    #[Route('/api/v1/service-section/{uuid}', methods: ['DELETE'])]
    public function deleteSection(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        // حذف بخش مجاز نیست: حذفِ آن سرویس‌های زیرمجموعه را هم پاک می‌کرد و سوابق
        // پرداخت/فاکتور به همان سرویس‌ها ارجاع دارند. فقط غیرفعال‌کردن مجاز است
        // (PATCH active=false).
        return $this->error(
            ErrorCodes::ERR_SERVICE_ITEM_IN_USE,
            'حذف بخش ممکن نیست؛ برای حفظ سوابق پرداخت فقط می‌توانید آن را غیرفعال کنید.',
            409
        );
    }

    // ── Service Items ────────────────────────────────────────────────────────

    /** همه‌ی سرویس‌های owner در همه‌ی بخش‌ها — برای انتخاب/جستجوی سراسری. */
    #[Route('/api/v1/service-items', methods: ['GET'])]
    public function listAllItems(#[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'view');
        [$entityType, $entityId] = $this->resolveEntity($user);

        // A user with neither a doctor profile nor a clinic (admin, secretary,
        // representation, plain patient) resolves to EntityContext::unknown(),
        // whose id is null — findByEntity() declares int and fataled with a 500.
        // Same condition, same answer as assertServicesGate(): forbidden.
        if ($entityId === null) {
            throw new AppException(ErrorCodes::ERR_FORBIDDEN_001, null, 403);
        }

        return $this->success($this->serializeItems(
            $this->itemRepo->findByEntity($entityType, $entityId)
        ));
    }

    #[Route('/api/v1/service-items/{sectionUuid}', methods: ['GET'])]
    public function listItems(string $sectionUuid, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'view');
        [$entityType, $entityId] = $this->resolveEntity($user);

        $section = $this->sectionRepo->findByUuid($sectionUuid);
        if ($section === null || !$this->ownsSection($section, $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        return $this->success($this->serializeItems($this->itemRepo->findBySection($section)));
    }

    #[Route('/api/v1/service-item/{uuid}', methods: ['GET'])]
    public function getItem(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'view');
        [$entityType, $entityId] = $this->resolveEntity($user);

        $item = $this->itemRepo->findByUuid($uuid);
        if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        return $this->success($this->serializeItems([$item])[0]);
    }

    /** تاریخچه‌ی تغییرات یک خدمت — تازه‌ترین رویداد اول. */
    #[Route('/api/v1/service-item/{uuid}/audit-logs', methods: ['GET'])]
    public function listItemAuditLogs(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'view');
        [$entityType, $entityId] = $this->resolveEntity($user);

        $item = $this->itemRepo->findByUuid($uuid);
        if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        return $this->success(array_map(
            fn(ServiceItemAuditLog $l) => $l->toArray(),
            $this->auditLogRepo->findByItem($item)
        ));
    }

    #[Route('/api/v1/service-item', methods: ['POST'])]
    public function createItem(Request $request, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'create');
        [$entityType, $entityId] = $this->resolveEntity($user);
        $this->assertServicesGate($entityType, $entityId);

        $data        = json_decode($request->getContent(), true) ?? [];
        $sectionUuid = $data['section_uuid'] ?? '';
        $name        = trim($data['name'] ?? '');

        if ($name === '' || $sectionUuid === '') {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'section_uuid و name الزامی هستند', 422);
        }

        $section = $this->sectionRepo->findByUuid($sectionUuid);
        if ($section === null || !$this->ownsSection($section, $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, 'بخش یافت نشد', 404);
        }

        $item = new ServiceItem($section, $name, (int) ($data['price_rials'] ?? 0));

        $staffError = $this->applyStaffMembers($item, $data, $entityType, $entityId);
        if ($staffError !== null) {
            return $staffError;
        }

        if (isset($data['insurance_covered'])) {
            $item->setInsuranceCovered((bool) $data['insurance_covered']);
        }
        if (array_key_exists('duration_minutes', $data)) {
            $dm = $data['duration_minutes'];
            $item->setDurationMinutes(($dm === null || $dm === '') ? null : (int) $dm);
        }
        if (array_key_exists('bookable', $data)) {
            $item->setBookable((bool) $data['bookable']);
        }
        if (($categoryError = $this->applyServiceCategory($item, $data)) !== null) {
            return $categoryError;
        }
        $packageError = $this->applyInventoryPackage($item, $data, $entityType, $entityId);
        if ($packageError !== null) {
            return $packageError;
        }
        $consumableError = $this->applyConsumables($item, $data, $entityType, $entityId);
        if ($consumableError !== null) {
            return $consumableError;
        }

        $this->itemRepo->save($item);

        // قیمت سرویس همان تعرفه‌ی سال جاری است؛ هنگام ساخت، تعرفه‌ی سال جاری ثبت می‌شود.
        $this->tariffService->upsert($item->getId(), $this->tariffService->currentJalaliYear(), $item->getPriceRials());
        $this->auditService->logCreate($item, $user);

        return $this->success($this->serializeItems([$item])[0], 201);
    }

    #[Route('/api/v1/service-item/{uuid}', methods: ['PATCH'])]
    public function updateItem(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'update');
        [$entityType, $entityId] = $this->resolveEntity($user);

        $item = $this->itemRepo->findByUuid($uuid);
        if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        $data   = json_decode($request->getContent(), true) ?? [];
        $before = $this->auditService->snapshot($item);

        $priceChanged = false;
        if (isset($data['name']) && trim($data['name']) !== '')  { $item->setName(trim($data['name'])); }
        if (isset($data['price_rials']))                          { $item->setPriceRials((int) $data['price_rials']); $priceChanged = true; }
        if (isset($data['active']))                               { $item->setActive((bool) $data['active']); }
        if (array_key_exists('staff_uuids', $data) || array_key_exists('staff_uuid', $data)) {
            $staffError = $this->applyStaffMembers($item, $data, $entityType, $entityId);
            if ($staffError !== null) {
                return $staffError;
            }
        }
        if (isset($data['insurance_covered'])) {
            $item->setInsuranceCovered((bool) $data['insurance_covered']);
        }
        if (array_key_exists('duration_minutes', $data)) {
            $dm = $data['duration_minutes'];
            $item->setDurationMinutes(($dm === null || $dm === '') ? null : (int) $dm);
        }
        if (array_key_exists('bookable', $data)) {
            $item->setBookable((bool) $data['bookable']);
        }
        if (($categoryError = $this->applyServiceCategory($item, $data)) !== null) {
            return $categoryError;
        }
        $packageError = $this->applyInventoryPackage($item, $data, $entityType, $entityId);
        if ($packageError !== null) {
            return $packageError;
        }
        $consumableError = $this->applyConsumables($item, $data, $entityType, $entityId);
        if ($consumableError !== null) {
            return $consumableError;
        }

        $this->itemRepo->save($item);

        // اگر قیمت پایه تغییر کرد، تعرفه‌ی سال جاری هم همگام می‌شود (قیمت واحد).
        if ($priceChanged) {
            $this->tariffService->upsert($item->getId(), $this->tariffService->currentJalaliYear(), $item->getPriceRials());
        }

        $this->auditService->logChanges($item, $before, $this->auditService->snapshot($item), $user);

        return $this->success($this->serializeItems([$item])[0]);
    }

    #[Route('/api/v1/service-item/{uuid}', methods: ['DELETE'])]
    public function deleteItem(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        // حذف سرویس مجاز نیست: نوبت‌ها، جلسات، فاکتورها و سوابق پرداخت به سرویس
        // ارجاع دارند و حذف آن‌ها را یتیم/ناسازگار می‌کرد. فقط غیرفعال‌کردن مجاز است
        // (PATCH active=false) — سرویسِ غیرفعال در پذیرش جدید نمایش داده نمی‌شود ولی
        // سوابق حفظ می‌شوند.
        return $this->error(
            ErrorCodes::ERR_SERVICE_ITEM_IN_USE,
            'حذف سرویس ممکن نیست؛ برای حفظ سوابق پرداخت فقط می‌توانید آن را غیرفعال کنید.',
            409
        );
    }

    // ── Tariffs (تعرفه‌ی نسخه‌دار سالانه) ──────────────────────────────────────

    #[Route('/api/v1/service-items/{uuid}/tariffs', methods: ['GET'])]
    #[IsGranted('IS_AUTHENTICATED_FULLY')]
    public function listTariffs(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'view');
        [$entityType, $entityId] = $this->resolveEntity($user);

        $item = $this->itemRepo->findByUuid($uuid);
        if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        $tariffs = $this->tariffRepo->findByService($item->getId());

        return $this->success([
            'current_year'        => $this->tariffService->currentJalaliYear(),
            'default_price_rials' => $item->getPriceRials(),
            'data'                => array_map(fn($t) => $t->toArray(), $tariffs),
        ]);
    }

    #[Route('/api/v1/service-items/{uuid}/tariffs/{year}', methods: ['PUT'], requirements: ['year' => '\d+'])]
    #[IsGranted('IS_AUTHENTICATED_FULLY')]
    public function setTariff(string $uuid, int $year, Request $request, #[CurrentUser] User $user): JsonResponse
    {
        $this->denyServices($user, 'update');
        [$entityType, $entityId] = $this->resolveEntity($user);

        $item = $this->itemRepo->findByUuid($uuid);
        if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
            return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
        }

        if ($year < 1390 || $year > 1500) {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'سال نامعتبر است', 422);
        }

        $data  = json_decode($request->getContent(), true) ?? [];
        $price = (int) ($data['price_rials'] ?? 0);

        $tariff = $this->tariffService->upsert($item->getId(), $year, $price);

        // تعرفه‌ی سال جاری = قیمت پایه‌ی سرویس (قیمت واحد در همه‌جا).
        if ($year === $this->tariffService->currentJalaliYear()) {
            $item->setPriceRials($price);
            $this->itemRepo->save($item);
        }

        return $this->success(['data' => $tariff->toArray()]);
    }

    // ── Helpers ──────────────────────────────────────────────────────────────

    /**
     * Resolve and assign the service's personnel from the payload, scoped to the
     * tenant. Accepts `staff_uuids` (array, preferred) or the legacy single
     * `staff_uuid`. Returns a 422 JsonResponse if any staff is missing or not
     * owned by the tenant, otherwise null.
     */
    private function applyStaffMembers(ServiceItem $item, array $data, string $entityType, int $entityId): ?JsonResponse
    {
        $uuids = [];
        if (array_key_exists('staff_uuids', $data) && is_array($data['staff_uuids'])) {
            $uuids = $data['staff_uuids'];
        } elseif (!empty($data['staff_uuid'])) {
            $uuids = [$data['staff_uuid']];
        }

        $members = [];
        foreach (array_values(array_unique(array_filter($uuids))) as $uuid) {
            $staff = $this->staffRepo->findByUuid((string) $uuid);
            if ($staff === null || $staff->getEntityType() !== $entityType || $staff->getEntityId() !== $entityId) {
                return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پرسنل انتخاب‌شده متعلق به شما نیست', 422, 'staff_uuids');
            }
            $members[] = $staff;
        }

        $item->setStaffMembers($members);
        return null;
    }

    /**
     * صاحب سرویس‌های این درخواست. clinic_uuid درخواست (query یا body) مقدم است، بعد
     * محیط فعال کاربر، و در آخر نقش — منطق کامل در EntityContextResolver.
     *
     * @return array{0: string, 1: ?int}
     */
    private function resolveEntity(User $user): array
    {
        // EntityContextResolver منشی را مالکِ محیط نمی‌شناسد؛ محیطِ فعالِ او را
        // جداگانه به owner (کلینیک/پزشک) حل می‌کنیم. مجوز با denyUnlessGranted جداست.
        if ($user->hasRole('ROLE_SECRETARY')) {
            return $this->secretaryAccess->resolveOwnerEntity($user);
        }

        return $this->contextResolver->resolve($user, $this->requestedClinicUuid())->toEntityPair();
    }

    private function requestedClinicUuid(): ?string
    {
        $request = $this->requestStack->getCurrentRequest();
        if ($request === null) {
            return null;
        }

        $fromQuery = $request->query->get('clinic_uuid');
        if (is_string($fromQuery) && $fromQuery !== '') {
            return $fromQuery;
        }

        if (!in_array($request->getMethod(), ['POST', 'PATCH', 'PUT'], true)) {
            return null;
        }

        $body = json_decode($request->getContent(), true);

        return is_array($body) && is_string($body['clinic_uuid'] ?? null) && $body['clinic_uuid'] !== ''
            ? $body['clinic_uuid']
            : null;
    }

    private function assertServicesGate(string $entityType, ?int $entityId): void
    {
        if ($entityId === null) {
            throw new AppException(ErrorCodes::ERR_FORBIDDEN_001, null, 403);
        }

        if (!$this->subscriptionService->hasFeature($entityType, $entityId, 'services')) {
            throw new AppException(ErrorCodes::ERR_SUBSCRIPTION_REQUIRED, null, 403);
        }
    }

    private function ownsSection(ServiceSection $section, string $entityType, ?int $entityId): bool
    {
        return $entityId !== null
            && $section->getEntityType() === $entityType
            && $section->getEntityId() === $entityId;
    }
}
