<?php

namespace App\Http\Controllers\Educacion;

use App\Http\Controllers\Controller;
use App\Http\Requests\Educacion\CarreraRequest;
use App\Models\Educacion\Carrera;
use App\Services\SearchCarrera;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CarreraController extends Controller
{
    protected $searchCarrera;

    public function __construct(SearchCarrera $searchCarrera)
    {
        $this->searchCarrera = $searchCarrera;
    }

    public function getAll(Request $request): JsonResponse
    {
        $query = Carrera::query();
        $pagination = $request->input('pagination', 10);
        $search = $request->input('search');

        if ($search) {
            $query = $this->searchCarrera->buscarCarreras($search);
        }

        $carreras = $query->with('area', 'pivote_horarios_carreras_estudiantes')->latest()->paginate($pagination)->appends($request->query());

        return response()->json(
            [
                'carreras' => $carreras,
                'params' => $request->query() ?: null,
            ],
            200,
        );
    }

    public function show($id): JsonResponse
    {
        $carrera = Carrera::findOrFail($id);

        if (!$carrera) {
            return response()->json(['message' => 'Carrera no encontrado.'], 404);
        }

        return response()->json(
            [
                'carrera' => $carrera,
                'message' => 'Carrera: ' . $carrera->nombre . ', encontrado exitosamente!.',
            ],
            200,
        );
    }

    public function save(CarreraRequest $request): JsonResponse
    {
        $carrera = Carrera::create($request->validated());
        $carrera->save();
        return response()->json(
            [
                'carrera' => $carrera,
                'message' => 'La carrera: ' . $carrera->nombre . ', se ha creado exitosamente!.',
            ],
            201,
        );
    }

    public function update($id, CarreraRequest $request): JsonResponse
    {
        $carrera = Carrera::findOrFail($id);

        if (!$carrera) {
            return response()->json(['message' => 'La carrera' . $request->nombre . ', no encontrado.'], 404);
        }

        $carrera->update($request->validated());
        $carrera->save();

        return response()->json(
            [
                'carrera' => $carrera,
                'message' => 'La carrera: ' . $carrera->nombre . ', se ha actualizado exitosamente!.',
            ],
            200,
        );
    }

    public function delete($id): JsonResponse
    {
        $carrera = Carrera::findOrFail($id);

        if (!$carrera) {
            return response()->json(['message' => 'Carrera no encontrado.'], 404);
        }

        $carrera->delete();

        return response()->json(
            [
                'message' => 'La carrera: ' . $carrera->nombre . ', se ha eliminado exitosamente!.',
            ],
            200,
        );
    }
}
