<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\IndexQueryRequest;
use App\Http\Requests\SchoolRequest;
use App\Http\Resources\SchoolResource;
use App\Models\School;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SchoolController extends Controller
{

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

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

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

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

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

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

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

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

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

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

            return SchoolResource::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;
        }
    }
}
