<?php

namespace App\Specialty\Controller;

use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Specialty\Entity\Specialty;
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: 'Specialties')]
class SpecialtyController extends BaseController
{
    public function __construct(
        private readonly SpecialtyRepository $repo,
    ) {}

    #[Route('/api/v1/specialties', methods: ['GET'])]
    public function list(Request $request): JsonResponse
    {
        $parentId = $request->query->get('parent_id');
        $items = array_map(
            fn(Specialty $s) => $s->toArray(),
            $this->repo->findActive($parentId !== null ? (int) $parentId : null)
        );
        return $this->success(['data' => $items]);
    }

    #[OA\Get(
        path: '/api/v1/specialties/doctor-counts',
        summary: 'Active specialties with the number of doctors (optionally scoped to a city)',
        parameters: [
            new OA\Parameter(name: 'city_id', in: 'query', required: false, schema: new OA\Schema(type: 'integer')),
        ],
        responses: [
            new OA\Response(response: 200, description: 'Specialties with number_of_doctors'),
        ]
    )]
    #[Route('/api/v1/specialties/doctor-counts', methods: ['GET'])]
    public function doctorCounts(Request $request): JsonResponse
    {
        $cityId = $request->query->get('city_id');
        $counts = $this->repo->doctorCountsByCity($cityId !== null ? (int) $cityId : null);

        $items = array_map(function (Specialty $s) use ($counts) {
            $arr = $s->toArray();
            $arr['number_of_doctors'] = $counts[$s->getId()] ?? 0;
            return $arr;
        }, $this->repo->findActive(null));

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

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

    #[Route('/api/v1/admin/specialty', 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);
        if ($this->repo->findBySlug($slug) !== null) {
            $slug = $slug . '-' . time();
        }

        $parent = null;
        if (!empty($data['parent_id'])) {
            $parent = $this->repo->find((int) $data['parent_id']);
        }

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

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

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

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

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

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

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

    #[Route('/api/v1/admin/specialties', 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', ''));

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

        if ($search !== '') {
            $qb->andWhere('s.name LIKE :s')->setParameter('s', '%' . $search . '%');
        }

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

        return $this->paginated(
            array_map(fn(Specialty $s) => $s->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 ?: 'specialty-' . time();
    }
}
