<?php

namespace App\DoctorService\Controller;

use App\DoctorService\Entity\DoctorService;
use App\DoctorService\Repository\DoctorServiceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Specialty\Repository\SpecialtyRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use OpenApi\Attributes as OA;

#[OA\Tag(name: 'Doctor Services')]
class DoctorServiceController extends BaseController
{
    public function __construct(
        private readonly DoctorServiceRepository $repo,
        private readonly SpecialtyRepository     $specialtyRepo,
    ) {}

    #[Route('/api/v1/doctor-services', methods: ['GET'])]
    public function list(Request $request): JsonResponse
    {
        $specialtyId = $request->query->get('specialty_id');
        $items = array_map(
            fn(DoctorService $ds) => $ds->toArray(),
            $this->repo->findActive($specialtyId !== null ? (int) $specialtyId : null)
        );
        return $this->success(['data' => $items]);
    }

    // ── Admin CRUD ────────────────────────────────────────────────────────────

    #[Route('/api/v1/admin/doctor-service', methods: ['POST'])]
    #[IsGranted('ROLE_ADMIN')]
    public function create(Request $request): JsonResponse
    {
        $data = json_decode($request->getContent(), true) ?? [];
        $name = trim($data['name'] ?? '');
        if ($name === '') {
            return $this->error(ErrorCodes::ERR_VALIDATION_001, 'name الزامی است', 422, 'name');
        }

        $slug = $data['slug'] ?? $this->slugify($name);

        $specialty = null;
        if (!empty($data['specialty_id'])) {
            $specialty = $this->specialtyRepo->find((int) $data['specialty_id']);
        }

        $service = new DoctorService($name, $slug, $specialty);
        if (isset($data['status'])) $service->setStatus((int) $data['status']);
        if (isset($data['weight'])) $service->setWeight((int) $data['weight']);

        $this->repo->save($service);
        return $this->success(['data' => $service->toArray()], 201);
    }

    #[Route('/api/v1/admin/doctor-service/{id}', methods: ['PATCH'])]
    #[IsGranted('ROLE_ADMIN')]
    public function update(int $id, Request $request): JsonResponse
    {
        $service = $this->repo->find($id);
        if ($service === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'خدمت یافت نشد', 404);
        }

        $data = json_decode($request->getContent(), true) ?? [];
        if (isset($data['name']))   $service->setName($data['name']);
        if (isset($data['slug']))   $service->setSlug($data['slug']);
        if (isset($data['status'])) $service->setStatus((int) $data['status']);
        if (isset($data['weight'])) $service->setWeight((int) $data['weight']);
        if (array_key_exists('specialty_id', $data)) {
            $specialty = $data['specialty_id'] ? $this->specialtyRepo->find((int) $data['specialty_id']) : null;
            $service->setSpecialty($specialty);
        }

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

    #[Route('/api/v1/admin/doctor-service/{id}', methods: ['DELETE'])]
    #[IsGranted('ROLE_ADMIN')]
    public function delete(int $id): JsonResponse
    {
        $service = $this->repo->find($id);
        if ($service === null) {
            return $this->error(ErrorCodes::ERR_VALIDATION_002, 'خدمت یافت نشد', 404);
        }

        $this->repo->remove($service);
        return $this->success(['message' => 'خدمت با موفقیت حذف شد']);
    }

    #[Route('/api/v1/admin/doctor-services', methods: ['GET'])]
    #[IsGranted('ROLE_ADMIN')]
    public function adminList(Request $request): JsonResponse
    {
        $page        = max(1, (int) $request->query->get('page', 1));
        $limit       = min(100, max(1, (int) $request->query->get('limit', 15)));
        $search      = trim((string) $request->query->get('search', ''));
        $specialtyId = $request->query->get('specialty_id');

        $qb = $this->repo->createQueryBuilder('ds');
        if ($request->query->get('sort') === 'id') {
            $qb->orderBy('ds.id', strtoupper((string) $request->query->get('order')) === 'DESC' ? 'DESC' : 'ASC');
        } else {
            $qb->orderBy('ds.weight', 'ASC')->addOrderBy('ds.name', 'ASC');
        }

        if ($search !== '') {
            $qb->andWhere('ds.name LIKE :s')->setParameter('s', '%' . $search . '%');
        }
        if ($specialtyId !== null && $specialtyId !== '') {
            $qb->andWhere('ds.specialty = :sp')->setParameter('sp', (int) $specialtyId);
        }

        $total = (clone $qb)->select('COUNT(ds.id)')->getQuery()->getSingleScalarResult();
        $rows  = $qb->setFirstResult(($page - 1) * $limit)->setMaxResults($limit)->getQuery()->getResult();

        return $this->paginated(
            array_map(fn(DoctorService $ds) => $ds->toArray(), $rows),
            (int) $total, $page, $limit
        );
    }

    private function slugify(string $text): string
    {
        $text = mb_strtolower(trim($text));
        $text = preg_replace('/\s+/', '-', $text);
        $text = preg_replace('/[^\p{L}\p{N}\-]/u', '', $text);
        return $text ?: 'service-' . time();
    }
}
