<?php

namespace App\Livewire\System;

use App\Livewire\Concerns\InteractsWithToasts;
use App\Services\Notifier;
use Illuminate\Support\Collection;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

/**
 * The bell menu, expanded.
 *
 * Product applications write into this same table when a shop signs up or
 * uploads a payment proof, which is how those events reach the team without a
 * queue or webhook between the two systems.
 */
#[Layout('layouts::app')]
#[Title('Notifications')]
class Notifications extends Component
{
    use InteractsWithToasts;

    #[Url(except: '')]
    public string $filter = '';   // unread

    public int $limit = 30;

    public function markAllRead(Notifier $notifier): void
    {
        $notifier->markAllRead(auth()->user());

        $this->toastSuccess('All notifications marked as read.');
    }

    public function markRead(string $id, Notifier $notifier): void
    {
        $notifier->markRead($id, auth()->user());
    }

    public function loadMore(): void
    {
        $this->limit += 30;
    }

    public function rows(Notifier $notifier): Collection
    {
        return $notifier->recentFor(auth()->user(), $this->limit)
            ->when($this->filter === 'unread', fn ($rows) => $rows->whereNull('read_at'));
    }

    public function render(Notifier $notifier)
    {
        return view('livewire.system.notifications', [
            'rows' => $this->rows($notifier),
            'unread' => $notifier->unreadCountFor(auth()->user()),
        ]);
    }
}
