<?php

namespace App\Livewire\Components;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\View\View;
use Livewire\Component;

/** @property-read Collection<int, DatabaseNotification> $notifications */
class NotificationsBell extends Component
{
    public bool $open = false;

    public function getUnreadCountProperty(): int
    {
        return auth()->user()?->unreadNotifications()->count() ?? 0;
    }

    /** @return Collection<int, DatabaseNotification> */
    public function getNotificationsProperty(): Collection
    {
        return auth()->user()?->notifications()->latest()->take(10)->get() ?? collect();
    }

    public function toggle(): void
    {
        $this->open = ! $this->open;
    }

    public function markRead(string $id): void
    {
        auth()->user()?->notifications()->where('id', $id)->first()?->markAsRead();
    }

    public function markAllRead(): void
    {
        auth()->user()?->unreadNotifications->markAsRead();
        $this->open = false;
    }

    public function render(): View
    {
        return view('livewire.components.notifications-bell');
    }
}
