<?php
declare(strict_types=1);

namespace App\Modules\Notifications;

use App\Core\Http\Request;
use App\Core\Http\Response;

final class NotificationApiController
{
    public function __construct(private readonly NotificationRepository $repository)
    {
    }

    public function unread(Request $request): Response
    {
        return Response::json([
            'ok' => true,
            'count' => $this->repository->unreadCount(),
            'items' => array_map(
                static fn (array $row): array => [
                    'id' => (int) ($row['id'] ?? 0),
                    'type' => (string) ($row['type'] ?? ''),
                    'title' => (string) ($row['title'] ?? ''),
                    'body' => (string) ($row['body'] ?? ''),
                    'target_url' => (string) ($row['target_url'] ?? ''),
                    'created_at' => (string) ($row['created_at'] ?? ''),
                ],
                $this->repository->recentUnread(10)
            ),
        ]);
    }

    public function markRead(Request $request): Response
    {
        $this->repository->markRead(max(0, (int) $request->input('id', 0)));

        return Response::json(['ok' => true, 'count' => $this->repository->unreadCount()]);
    }
}
