<?php

namespace App\Modules\Pilkades\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Http\Requests\Public\SearchVoterRequest;
use App\Modules\Pilkades\Repositories\Contracts\DesaRepositoryInterface;
use App\Modules\Pilkades\Services\VoterSearchService;
use Illuminate\Http\JsonResponse;

class VoterSearchController extends Controller
{
    public function __construct(
        protected DesaRepositoryInterface $desaRepository,
        protected VoterSearchService $voterSearchService,
    ) {}

    public function search(SearchVoterRequest $request, string $kabupaten, string $kecamatan, string $desa): JsonResponse
    {
        $desaModel = $this->desaRepository->findBySlug($kabupaten, $kecamatan, $desa);

        abort_if(! $desaModel || ! $desaModel->isPublished(), 404);

        $results = $this->voterSearchService->search(
            $request,
            $desaModel->id,
            $request->validated('type'),
            trim($request->validated('query')),
        );

        return response()->json(['data' => $results]);
    }
}
