<?php

namespace App\Location\Controller;

use App\Location\Entity\City;
use App\Location\Entity\Province;
use App\Location\Repository\CityRepository;
use App\Location\Repository\ProvinceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
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: 'Location')]
class LocationController extends BaseController
{
    public function __construct(
        private readonly ProvinceRepository $provinceRepo,
        private readonly CityRepository     $cityRepo,
    ) {}

    // ── Public endpoints ──────────────────────────────────────────────────────

    #[Route('/api/v1/provinces', methods: ['GET'])]
    public function provinces(): JsonResponse
    {
        $items = array_map(fn(Province $p) => $p->toArray(), $this->provinceRepo->findActive());
        return $this->success(['data' => $items]);
    }

    #[Route('/api/v1/cities', methods: ['GET'])]
    public function cities(Request $request): JsonResponse
    {
        $provinceId = $request->query->get('province_id');
        $items = array_map(
            fn(City $c) => $c->toArray(),
            $this->cityRepo->findActive($provinceId !== null ? (int) $provinceId : null)
        );
        return $this->success(['data' => $items]);
    }

    // ── Admin CRUD — Province ─────────────────────────────────────────────────

    #[Route('/api/v1/admin/province', methods: ['POST'])]
    #[IsGranted('ROLE_ADMIN')]
    public function createProvince(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');
        }

        $province = new Province($name);
        if (isset($data['status'])) $province->setStatus((int) $data['status']);
        if (isset($data['weight'])) $province->setWeight((int) $data['weight']);

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

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

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

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

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

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

    // ── Admin CRUD — City ─────────────────────────────────────────────────────

    #[Route('/api/v1/admin/city', methods: ['POST'])]
    #[IsGranted('ROLE_ADMIN')]
    public function createCity(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');
        }

        $province = null;
        if (!empty($data['province_id'])) {
            $province = $this->provinceRepo->find((int) $data['province_id']);
        }

        $city = new City($name, $province);
        $this->applyCityData($city, $data);
        $this->cityRepo->save($city);

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

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

        $data = json_decode($request->getContent(), true) ?? [];
        if (isset($data['name'])) $city->setName($data['name']);
        if (array_key_exists('province_id', $data)) {
            $province = $data['province_id'] ? $this->provinceRepo->find((int) $data['province_id']) : null;
            $city->setProvince($province);
        }
        $this->applyCityData($city, $data);
        $this->cityRepo->save($city);

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

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

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

    // ── Admin paginated lists ─────────────────────────────────────────────────

    #[Route('/api/v1/admin/provinces', methods: ['GET'])]
    #[IsGranted('ROLE_ADMIN')]
    public function adminProvinces(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->provinceRepo->createQueryBuilder('p');
        if ($request->query->get('sort') === 'id') {
            $qb->orderBy('p.id', strtoupper((string) $request->query->get('order')) === 'DESC' ? 'DESC' : 'ASC');
        } else {
            $qb->orderBy('p.weight', 'ASC')->addOrderBy('p.name', 'ASC');
        }
        if ($search !== '') {
            $qb->andWhere('p.name LIKE :s')->setParameter('s', '%' . $search . '%');
        }

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

        $items = array_map(fn(array $r) => [
            'id' => $r['id'], 'uuid' => $r['uuid'], 'name' => $r['name'],
            'status' => $r['status'], 'weight' => $r['weight'],
        ], $rows);

        return $this->paginated($items, (int) $total, $page, $limit);
    }

    #[Route('/api/v1/admin/cities', methods: ['GET'])]
    #[IsGranted('ROLE_ADMIN')]
    public function adminCities(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', ''));
        $provinceId = $request->query->get('province_id');

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

        if ($search !== '') {
            $qb->andWhere('c.name LIKE :s')->setParameter('s', '%' . $search . '%');
        }
        if ($provinceId !== null && $provinceId !== '') {
            $qb->andWhere('c.province = :province')->setParameter('province', (int) $provinceId);
        }

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

        $items = array_map(fn(City $c) => $c->toArray(), $cities);

        return $this->paginated($items, (int) $total, $page, $limit);
    }

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

    private function applyCityData(City $city, array $data): void
    {
        if (isset($data['status']))              $city->setStatus((int) $data['status']);
        if (isset($data['weight']))              $city->setWeight((int) $data['weight']);
        if (array_key_exists('representation_id', $data))
            $city->setRepresentationId($data['representation_id'] !== null ? (int) $data['representation_id'] : null);
        if (array_key_exists('site_name', $data))      $city->setSiteName($data['site_name']);
        if (array_key_exists('title', $data))          $city->setTitle($data['title']);
        if (array_key_exists('contact_phone', $data))  $city->setContactPhone($data['contact_phone']);
        if (array_key_exists('email', $data))          $city->setEmail($data['email']);
        if (array_key_exists('description', $data))    $city->setDescription($data['description']);
        if (array_key_exists('slogan', $data))         $city->setSlogan($data['slogan']);
        if (array_key_exists('domain', $data))         $city->setDomain($data['domain']);
        if (array_key_exists('keywords', $data))       $city->setKeywords($data['keywords']);
        if (array_key_exists('footer_description', $data)) $city->setFooterDescription($data['footer_description']);
        if (array_key_exists('social_media', $data))   $city->setSocialMedia($data['social_media']);
        if (array_key_exists('logo_url', $data))       $city->setLogoUrl($data['logo_url']);
    }
}
