<?php

declare(strict_types=1);

namespace ApiModel\Action;

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

final class NotificationAction
{
    public function __construct(private readonly NotificationService $notifications) {}

    /** @return array<string, mixed> */
    public function list(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['MANAGER', 'ADMINISTRADOR']);
        $q = $request->getQueryParams();
        $page = max(1, (int) ($q['page'] ?? 1));
        $limit = min(100, max(1, (int) ($q['limit'] ?? 30)));
        $unreadOnly = filter_var($q['unread_only'] ?? false, FILTER_VALIDATE_BOOLEAN);

        return $this->notifications->listForUser($u['userId'], $page, $limit, $unreadOnly);
    }

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

        return $this->notifications->markAllRead($u['userId']);
    }

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

        return $this->notifications->markOneRead($notificationId, $u['userId']);
    }
}
