<?php

namespace App\ClinicService\Controller;

use App\Auth\Entity\User;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceSection;
use App\Insurance\Entity\TenantServiceCoverage;
use App\ClinicService\Entity\Tariff;
use Doctrine\ORM\EntityManagerInterface;
use App\ClinicService\Repository\ServiceItemRepository;
use App\ClinicService\Repository\ServiceSectionRepository;
use App\ClinicService\Repository\TariffRepository;
use App\ClinicService\Service\TariffService;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Shared\Constant\ErrorCodes;
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\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 DoctorRepository         $doctorRepo,
        private readonly ClinicRepository         $clinicRepo,
        private readonly TariffRepository         $tariffRepo,
        private readonly TariffService            $tariffService,
        private readonly EntityManagerInterface   $em,
    ) {}

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

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

        $sections = array_map(
            fn(ServiceSection $s) => $s->toArray(),
            $this->sectionRepo->findByEntity($entityType, $entityId)
        );

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

    #[Route('/api/v1/service-section', methods: ['POST'])]
    public function createSection(Request $request, #[CurrentUser] User $user): JsonResponse
    {
        [$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
    {
        [$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
    {
        [$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);
        }

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

        return $this->success(['message' => 'بخش حذف شد']);
    }

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

    #[Route('/api/v1/service-items/{sectionUuid}', methods: ['GET'])]
    public function listItems(string $sectionUuid, #[CurrentUser] User $user): JsonResponse
    {
        [$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);
        }

        $items = array_map(
            fn(ServiceItem $i) => $i->toArray(),
            $this->itemRepo->findBySection($section)
        );

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

    #[Route('/api/v1/service-item', methods: ['POST'])]
    public function createItem(Request $request, #[CurrentUser] User $user): JsonResponse
    {
        [$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));

        if (!empty($data['staff_uuid'])) {
            $staff = $this->staffRepo->findByUuid($data['staff_uuid']);
            if ($staff === null || $staff->getEntityType() !== $entityType || $staff->getEntityId() !== $entityId) {
                return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پرسنل انتخاب‌شده متعلق به شما نیست', 422, 'staff_uuid');
            }
            $item->setStaff($staff);
        }

        if (isset($data['insurance_covered'])) {
            $item->setInsuranceCovered((bool) $data['insurance_covered']);
        }
        if (array_key_exists('insurance_price_rials', $data)) {
            $item->setInsurancePriceRials($data['insurance_price_rials'] !== null ? (int) $data['insurance_price_rials'] : null);
        }
        if (array_key_exists('duration_minutes', $data)) {
            $dm = $data['duration_minutes'];
            $item->setDurationMinutes(($dm === null || $dm === '') ? null : (int) $dm);
        }

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

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

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

    #[Route('/api/v1/service-item/{uuid}', methods: ['PATCH'])]
    public function updateItem(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
    {
        [$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) ?? [];

        $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_uuid', $data)) {
            $staff = null;
            if ($data['staff_uuid']) {
                $staff = $this->staffRepo->findByUuid($data['staff_uuid']);
                if ($staff === null || $staff->getEntityType() !== $entityType || $staff->getEntityId() !== $entityId) {
                    return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پرسنل انتخاب‌شده متعلق به شما نیست', 422, 'staff_uuid');
                }
            }
            $item->setStaff($staff);
        }
        if (isset($data['insurance_covered'])) {
            $item->setInsuranceCovered((bool) $data['insurance_covered']);
        }
        if (array_key_exists('insurance_price_rials', $data)) {
            $item->setInsurancePriceRials($data['insurance_price_rials'] !== null ? (int) $data['insurance_price_rials'] : null);
        }
        if (array_key_exists('duration_minutes', $data)) {
            $dm = $data['duration_minutes'];
            $item->setDurationMinutes(($dm === null || $dm === '') ? null : (int) $dm);
        }

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

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

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

    #[Route('/api/v1/service-item/{uuid}', methods: ['DELETE'])]
    public function deleteItem(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        [$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);
        }

        // Tariff and tenant-coverage rows reference the item by a raw int (no FK),
        // so they would orphan on delete. Remove the item's config rows first.
        $itemId = $item->getId();
        $this->em->createQuery('DELETE FROM ' . Tariff::class . ' t WHERE t.serviceItemId = :id')
            ->setParameter('id', $itemId)->execute();
        $this->em->createQuery('DELETE FROM ' . TenantServiceCoverage::class . ' c WHERE c.serviceItemId = :id')
            ->setParameter('id', $itemId)->execute();

        try {
            $this->itemRepo->remove($item);
        } catch (\Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException) {
            return $this->error(ErrorCodes::ERR_SERVICE_ITEM_IN_USE, ErrorCodes::message(ErrorCodes::ERR_SERVICE_ITEM_IN_USE), 409);
        }

        return $this->success(['message' => 'سرویس حذف شد']);
    }

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

    #[Route('/api/v1/service-items/{uuid}/tariffs', methods: ['GET'])]
    #[IsGranted('IS_AUTHENTICATED_FULLY')]
    public function listTariffs(string $uuid, #[CurrentUser] User $user): JsonResponse
    {
        [$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
    {
        [$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 ──────────────────────────────────────────────────────────────

    private function resolveEntity(User $user): array
    {
        if ($user->hasRole('ROLE_DOCTOR')) {
            $doctor = $this->doctorRepo->findByUser($user);
            return $doctor !== null ? ['doctor', $doctor->getId()] : ['doctor', null];
        }

        if ($user->hasRole('ROLE_CLINIC')) {
            $clinic = $this->clinicRepo->findByUser($user);
            return $clinic !== null ? ['clinic', $clinic->getId()] : ['clinic', null];
        }

        return ['unknown', 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;
    }
}
