<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;
use App\Repositories\UserRepository;

final class UserController
{
    public function index(): void
    {
        Auth::requireRole(['admin']);
        Response::json((new UserRepository())->all());
    }

    public function store(): void
    {
        Auth::requireRole(['admin']);
        $data = Request::json();
        $errors = Validator::require($data, ['name', 'email', 'password', 'role']);
        if ($errors) {
            Response::error('Datos inválidos', 422, $errors);
            return;
        }

        Response::json((new UserRepository())->create($data), 201);
    }

    public function update(array $params): void
    {
        Auth::requireRole(['admin']);
        $user = (new UserRepository())->update((int) $params['id'], Request::json());
        if (!$user) {
            Response::error('Usuario no encontrado', 404);
            return;
        }

        Response::json($user);
    }
}
