<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Desa;
use App\Modules\Pilkades\Repositories\Contracts\DesaRepositoryInterface;
use App\Modules\Pilkades\Services\DesaService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class DesaApiController extends Controller
{
    public function __construct(
        protected DesaRepositoryInterface $desaRepository,
        protected DesaService $desaService,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $query = Desa::with('kecamatan.kabupaten');

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

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

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

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

        $desa = $this->desaService->create($data);

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

    public function update(Request $request, Desa $desa): JsonResponse
    {
        $data = $request->validate([
            'nama' => ['sometimes', 'required', 'string', 'max:255'],
            'tanggal_pilkades' => ['nullable', 'date'],
            'is_active' => ['sometimes', 'boolean'],
            'status' => ['sometimes', Rule::in(['draft', 'published', 'suspended'])],
        ]);

        $updated = $this->desaService->update($desa, $data);

        return response()->json($updated);
    }

    public function destroy(Desa $desa): JsonResponse
    {
        $desa->delete();

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