<?php

namespace App\Http\Controllers;

use App\Models\ElectionEvent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ElectionEventController extends Controller
{
    public function index(): JsonResponse
    {
        $events = ElectionEvent::withCount('voteTallies')
            ->orderByDesc('created_at')
            ->get();

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

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'election_date' => 'nullable|date',
            'status' => 'sometimes|in:draft,active,closed',
            'notes' => 'nullable|string|max:2000',
        ]);

        $event = ElectionEvent::create($data);

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

    public function show(ElectionEvent $electionEvent): JsonResponse
    {
        $electionEvent->loadCount('voteTallies');

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

    public function update(Request $request, ElectionEvent $electionEvent): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'election_date' => 'nullable|date',
            'status' => 'required|in:draft,active,closed',
            'notes' => 'nullable|string|max:2000',
        ]);

        $electionEvent->update($data);

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

    public function destroy(ElectionEvent $electionEvent): JsonResponse
    {
        $electionEvent->delete();

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