<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\NotificationService;

class NotificationController extends BaseController
{
    private NotificationService $notificationService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->notificationService = new NotificationService();
    }

    public function index(): void
    {
        $page = (int) ($this->request->query('page', 1));
        $perPage = (int) ($this->request->query('per_page', 20));

        $result = $this->notificationService->getUserNotifications($this->getAuthUserId(), $page, $perPage);

        Response::json([
            'success' => true,
            'message' => 'Notificaciones consultadas correctamente',
            'data' => $result['items'],
            'unread' => $result['unread'],
            'pagination' => [
                'page' => $result['page'],
                'per_page' => $result['per_page'],
                'total' => $result['total'],
                'total_pages' => $result['total_pages'],
            ],
        ]);
    }

    public function markAsRead(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->notificationService->markAsRead($id);
            Response::success(null, 'Notificación marcada como leída');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function markAllAsRead(): void
    {
        $this->notificationService->markAllAsRead($this->getAuthUserId());
        Response::success(null, 'Todas las notificaciones marcadas como leídas');
    }
}
