<?php

namespace App\Http\Controllers;

use App\Models\PoliticalParty;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PoliticalPartyController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $parties = PoliticalParty::search($request->input('search'))
            ->orderBy('name')
            ->paginate($request->integer('per_page', 15));

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

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'acronym' => 'required|string|max:20',
            'logo' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('parties', 'public');
        }

        $party = PoliticalParty::create($data);

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

    public function show(PoliticalParty $politicalParty): JsonResponse
    {
        return response()->json($politicalParty);
    }

    public function update(Request $request, PoliticalParty $politicalParty): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'acronym' => 'required|string|max:20',
            'logo' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('logo')) {
            if ($politicalParty->logo) {
                Storage::disk('public')->delete($politicalParty->logo);
            }
            $data['logo'] = $request->file('logo')->store('parties', 'public');
        }

        $politicalParty->update($data);

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

    public function destroy(PoliticalParty $politicalParty): JsonResponse
    {
        if ($politicalParty->logo) {
            Storage::disk('public')->delete($politicalParty->logo);
        }

        $politicalParty->delete();

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