<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\Notification\NotificationService;

class NotificationController extends BaseController
{
    private NotificationService $notifications;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->notifications = new NotificationService();
    }

    public function index()
    {
        $user = $this->currentUser();
        $unreadOnly = $this->request->getGet('unread') === '1';
        $page = (int) ($this->request->getGet('page') ?? 1);

        return $this->jsonSuccess(['notifications' => $this->notifications->forUser($user->id, $unreadOnly, $page)]);
    }

    public function markRead(int $notificationId)
    {
        $user = $this->currentUser();
        $success = $this->notifications->markRead($notificationId, $user->id);

        return $success
            ? $this->jsonSuccess(['message' => 'Marked as read.'])
            : $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'Notification not found.']], 404);
    }

    public function updatePreferences()
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);

        $this->notifications->updatePreferences($user->id, $input);
        return $this->jsonSuccess(['message' => 'Preferences updated.']);
    }
}
