<?php

declare(strict_types=1);

namespace ApiModel\Action;

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

final class CanjeAction
{
    public function __construct(private readonly CanjeService $service) {}

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

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

    /** @return array<string, mixed> */
    public function registrar(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        // Redeeming is allowed for HARDWARE STORE (ferretería) clerks and ADMINISTRADOR (for testing/override)
        AuthContext::requireRoles($u, ['HARDWARE STORE', 'ADMINISTRADOR']);

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

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