<?php

namespace App\Services;

use App\Models\Notification;
use Illuminate\Database\Eloquent\Collection;

class NotificationService
{
    public function getByUser(int $userId): Collection
    {
        return Notification::where('user_id', $userId)
            ->orderBy('read', 'asc')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function findById(int $id): Notification
    {
        return Notification::findOrFail($id);
    }

    public function create(array $data): Notification
    {
        return Notification::create($data);
    }

    public function delete(Notification $notification): void
    {
        $notification->delete();
    }

    //

    public function markAsRead(Notification $notification): Notification
    {
        $notification->update([
            'read'    => true,
            'read_at' => now(),
        ]);

        return $notification;
    }

    public function markAllAsRead(int $userId): void
    {
        Notification::where('user_id', $userId)
            ->where('read', false)
            ->update([
                'read'    => true,
                'read_at' => now(),
            ]);
    }

    public function unreadCount(int $userId): int
    {
        return Notification::where('user_id', $userId)
            ->where('read', false)
            ->count();
    }
}
