<?php

namespace App\Modules\Pilkades\Http\Controllers\Api\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Kecamatan;
use App\Modules\Pilkades\Services\SlugGeneratorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class KecamatanApiController extends Controller
{
    public function __construct(protected SlugGeneratorService $slugGenerator) {}

    public function index(Request $request): JsonResponse
    {
        $query = Kecamatan::with('kabupaten')->withCount('desa');

        if ($request->filled('kabupaten_id')) {
            $query->where('kabupaten_id', $request->string('kabupaten_id'));
        }

        return response()->json($query->paginate(20));
    }

    public function show(Kecamatan $kecamatan): JsonResponse
    {
        return response()->json($kecamatan->load('kabupaten'));
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'kabupaten_id' => ['required', 'uuid', 'exists:kabupaten,id'],
            'nama' => ['required', 'string', 'max:255'],
            'kode_wilayah' => ['nullable', 'string', 'max:50'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $data['slug'] = $this->slugGenerator->generate(
            Kecamatan::class, $data['nama'], 'kabupaten_id', $data['kabupaten_id'],
        );

        $kecamatan = Kecamatan::create($data);

        return response()->json($kecamatan, 201);
    }

    public function update(Request $request, Kecamatan $kecamatan): JsonResponse
    {
        $data = $request->validate([
            'kabupaten_id' => ['sometimes', 'uuid', 'exists:kabupaten,id'],
            'nama' => ['sometimes', 'required', 'string', 'max:255'],
            'kode_wilayah' => ['nullable', 'string', 'max:50'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $kabupatenId = $data['kabupaten_id'] ?? $kecamatan->kabupaten_id;

        if (! empty($data['nama']) && $data['nama'] !== $kecamatan->nama) {
            $data['slug'] = $this->slugGenerator->generate(
                Kecamatan::class, $data['nama'], 'kabupaten_id', $kabupatenId,
            );
        }

        $kecamatan->update($data);

        return response()->json($kecamatan->fresh());
    }

    public function destroy(Kecamatan $kecamatan): JsonResponse
    {
        $kecamatan->delete();

        return response()->json(null, 204);
    }
}
