<?php

declare(strict_types=1);

namespace ApiModel\Action;

use ApiModel\Service\FerreteriaService;
use ApiModel\Shared\Http\HttpUtil;
use ApiModel\Shared\Support\AuthContext;
use Psr\Http\Message\ServerRequestInterface;

final class FerreteriaAction
{
    public function __construct(private readonly FerreteriaService $service) {}

    /** @return list<array<string, mixed>> */
    public function listar(ServerRequestInterface $request): array
    {
        AuthContext::jwtUser($request);
        $params = $request->getQueryParams();
        $activeOnly = isset($params['active']) && in_array((string) $params['active'], ['1', 'true'], true);

        return $this->service->listFerreterias($activeOnly ? true : null);
    }

    /** @return array<string, mixed> */
    public function obtener(ServerRequestInterface $request, string $id): array
    {
        AuthContext::jwtUser($request);

        return $this->service->getFerreteria($id);
    }

    /** @return array<string, mixed> */
    public function crear(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['ADMINISTRADOR']);

        return $this->service->createFerreteria(HttpUtil::parseJson($request));
    }

    /** @return array<string, mixed> */
    public function actualizar(ServerRequestInterface $request, string $id): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['ADMINISTRADOR']);

        return $this->service->updateFerreteria($id, HttpUtil::parseJson($request));
    }
}
