<?php

declare(strict_types=1);

namespace ApiModel\Action;

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

final class CertificadoAction
{
    public function __construct(private readonly CertificadoService $service) {}

    /** @return list<array<string, mixed>> */
    public function listar(ServerRequestInterface $request): array
    {
        AuthContext::jwtUser($request);
        $filters = $request->getQueryParams();

        return $this->service->listCertificados($filters);
    }

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

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

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

        return $this->service->consultarParaCanje($id, $u['userId']);
    }

    /** @return array<string, mixed> */
    public function consultarDetallePorCodigo(ServerRequestInterface $request, string $codigo): array
    {
        $u = AuthContext::jwtUser($request);

        return $this->service->consultarParaCanjePorCodigo($codigo, $u['userId']);
    }

    /** @return array<string, mixed> */
    public function crear(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        // Emitting certificates is allowed for ADMIN and REGISTRADOR roles
        AuthContext::requireRoles($u, ['ADMINISTRADOR', 'REGISTRADOR']);

        $data = HttpUtil::parseJson($request);

        return $this->service->createCertificado($data, $u['userId']);
    }

    /** @return array<string, mixed> */
    public function anular(ServerRequestInterface $request, string $id): array
    {
        $u = AuthContext::jwtUser($request);
        // Only ADMINISTRADOR role is allowed to cancel/revoke certificates
        AuthContext::requireRoles($u, ['ADMINISTRADOR']);

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