<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\PlayerApi\Services\PlayerNotificationService;

final class NotificationController extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function list(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $page = max(1, $this->queryInt('page', 1));
        $perPage = min(50, max(1, $this->queryInt('per_page', 25)));
        $category = $request->get('category');
        $isRead = $request->get('is_read') !== null ? (bool) (int) $request->get('is_read') : null;

        $result = PlayerNotificationService::getForPlayer(
            (int) $player->id,
            $category,
            $isRead,
            $page,
            $perPage
        );

        return $this->paginatedResponse(
            $result['data'],
            $result['pagination']['total'],
            $result['pagination']['current_page'],
            $result['pagination']['per_page']
        );
    }

    public function markRead(Request $request, string $id): Response
    {
        $player = App::getInstance()->currentPlayer();
        PlayerNotificationService::markRead((int) $id, (int) $player->id);
        return $this->successResponse(['read' => true]);
    }

    public function markAllRead(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        PlayerNotificationService::markAllRead((int) $player->id);
        return $this->successResponse(['read_all' => true]);
    }

    public function unreadCount(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $count = PlayerNotificationService::unreadCount((int) $player->id);
        return $this->successResponse(['unread_count' => $count]);
    }
}
