<?php

namespace App\Http\Controllers;

use App\Models\Configuracion;
use App\Services\ConfiguracionService;
use App\Traits\ApiResponse;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

final class ConfiguracionController extends Controller
{
    use ApiResponse;

    public function __construct(
        protected ConfiguracionService $service
    ) {
    }

    public function index()
    {

        $configuraciones = Configuracion::select(['display_name', 'clave', 'valor', 'descripcion', 'tipo', 'updated_at', 'uuid'])->orderBy('display_name')->get();

        return view('configuracion.index', ['configuraciones' => $configuraciones]);
    }

    public function update(Request $request)
    {

        $validation_data = $this->service->getValidationRules($request);

        $validator = Validator::make($request->all(), $validation_data['rules'], $validation_data['messages']);

        if ($validator->fails()) {
            return $this->errorMessage(data: $validator->errors(), code: 400);
        }

        try {

            $this->service->update($request);

        } catch (Exception $e) {

            throw $e;

            return $this->errorMessage(message: 'Error al actualizar la configuración.');
        }

        return $this->successMessage(message: 'Configuración actualizada correctamente.');
    }
}
