<?php

namespace App\Tag\Controller;

use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Tag\Entity\Tag;
use App\Tag\Repository\TagRepository;
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: 'Tags')]
class TagController extends BaseController
{
    public function __construct(
        private readonly TagRepository $repo,
    ) {}

    #[Route('/api/v1/tags', methods: ['GET'])]
    public function list(): JsonResponse
    {
        $items = array_map(fn(Tag $t) => $t->toArray(), $this->repo->findActive());
        return $this->success(['data' => $items]);
    }

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

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

        $tag = new Tag($name, $slug);
        if (isset($data['status'])) $tag->setStatus((int) $data['status']);

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

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

        $data = json_decode($request->getContent(), true) ?? [];
        if (isset($data['name']))   $tag->setName($data['name']);
        if (isset($data['slug']))   $tag->setSlug($data['slug']);
        if (isset($data['status'])) $tag->setStatus((int) $data['status']);

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

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

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

    #[Route('/api/v1/admin/tags', 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('t');
        if ($request->query->get('sort') === 'id') {
            $qb->orderBy('t.id', strtoupper((string) $request->query->get('order')) === 'DESC' ? 'DESC' : 'ASC');
        } else {
            $qb->orderBy('t.name', 'ASC');
        }
        if ($search !== '') {
            $qb->andWhere('t.name LIKE :s')->setParameter('s', '%' . $search . '%');
        }

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

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