<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Notifications\NotificationsAuthorizationPolicy;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(NotificationsAuthorizationPolicy::ABILITY_VIEW);

if (requestInput()->method() !== 'GET') {
    http_response_code(405);
    Router::json(['ok' => false, 'error' => 'method_not_allowed']);
    return;
}

$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
$tenantId = (int) (($session['current_tenant']['id'] ?? 0));
if ($userId <= 0) {
    http_response_code(401);
    Router::json(['ok' => false, 'error' => 'unauthorized']);
    return;
}

$service = app(NotificationService::class);
$unreadCount = $service->unreadCount($userId, $tenantId > 0 ? $tenantId : null);

app(SessionStoreInterface::class)->set('module.notifications.unread_count', $unreadCount);

Router::json(['ok' => true, 'unread_count' => $unreadCount]);
