<?php

namespace App\Services\Notifications;

use App\Models\UserNotification;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class NotificationUserListService
{
    public function listForUser(int $userId, array $filters): array
    {
        $perPage = (int) ($filters['per_page'] ?? 25);
        $page = (int) ($filters['page'] ?? 1);
        $sortBy = (string) ($filters['sort_by'] ?? 'created_at');
        $sortDir = strtolower((string) ($filters['sort_dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';

        $allowedSorts = ['created_at', 'scheduled_at', 'priority'];
        if (!in_array($sortBy, $allowedSorts, true)) {
            $sortBy = 'created_at';
        }

        $query = UserNotification::query()
            ->select([
                'user_notifications.*',
                'notifications.title',
                'notifications.message',
                'notifications.priority',
                'notifications.scheduled_at',
                'notifications.expires_at',
                'notifications.target_group',
            ])
            ->join('notifications', 'notifications.id', '=', 'user_notifications.notification_id')
            ->where('user_notifications.user_id', $userId);

        if (isset($filters['read'])) {
            $read = filter_var($filters['read'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
            if ($read !== null) {
                $query->where('user_notifications.is_read', $read ? 1 : 0);
            }
        }

        $paginator = $query
            ->orderBy('notifications.' . $sortBy, $sortDir)
            ->paginate($perPage, ['*'], 'page', $page);

        return [
            'notifications' => $paginator,
            'pagination' => $this->paginationPayload($paginator),
        ];
    }

    private function paginationPayload(LengthAwarePaginator $paginator): array
    {
        return [
            'current_page' => $paginator->currentPage(),
            'per_page' => $paginator->perPage(),
            'total' => $paginator->total(),
            'total_pages' => $paginator->lastPage(),
        ];
    }
}
