<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\DistrictRequest;
use App\Http\Requests\IndexQueryRequest;
use App\Http\Resources\DistrictResource;
use App\Models\District;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DistrictController extends Controller
{

    private array $messages = [
        'index'          => 'Lista de Distritos obtenidos exitosamente',
        'store'          => 'Distrito creado exitosamente',
        'show'           => 'Distrito obtenido exitosamente',
        'update'         => 'Distrito actualizado exitosamente',
        'destroy'        => 'Distrito eliminado exitosamente',
        'not_found'      => 'Distrito no encontrado',
        'cannot_destroy' => 'No se puede eliminar el Distrito porque esta en uso',
    ];

    public function index(IndexQueryRequest $request): JsonResponse
    {
        $items = District::query()
            ->included()
            ->search()
            ->filter()
            ->sort()
            ->paginated();

        return DistrictResource::collection($items)
            ->additional([
                'success' => true,
                'message' => $this->messages['index']
            ])
            ->response();
    }

    public function store(DistrictRequest $request): JsonResponse
    {
        $item = District::create($request->validated());

        return DistrictResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['store']
            ])
            ->response()
            ->setStatusCode(201);
    }

    public function show(int $id): JsonResponse
    {
        $item = District::findOrAbort($id, $this->messages['not_found']);

        return DistrictResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['show']
            ])
            ->response();
    }

    public function update(DistrictRequest $request, int $id): JsonResponse
    {
        $item = District::findOrAbort($id, $this->messages['not_found']);
        $item->update($request->validated());

        return DistrictResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['update']
            ])
            ->response();
    }

    public function destroy(int $id): JsonResponse
    {
        try {
            $item = District::findOrAbort($id, $this->messages['not_found']);
            $item->delete();

            return DistrictResource::make($item)
                ->additional([
                    'success' => true,
                    'message' => $this->messages['destroy']
                ])
                ->response();
        } catch (QueryException $e) {
            // Foreign key constraint violation
            if ($e->getCode() === '23000') {
                return response()->json([
                    'success' => false,
                    'message' => $this->messages['cannot_destroy']
                ], 409);
            }

            // Re-lanzar otros errores para que el handler global los maneje
            throw $e;
        }
    }
}
