<?php

namespace App\Livewire\Portal;

use App\Domain\Notification\Models\NotificationLog;
use App\Livewire\Portal\Concerns\PortalScreen;
use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

/**
 * Notification history and read state.
 *
 * Reads notification_logs directly rather than inventing a second store: the
 * twelve existing listeners already write here, and until S1 widened the
 * channel CHECK every one of those writes with channel 'push' raised a 23514.
 */
#[Layout('layouts.portal')]
#[Title('الإشعارات')]
class PortalNotifications extends Component
{
    use PortalScreen, WithPagination;

    public function mount(): void
    {
        $this->authorizePortal();
    }

    public function markRead(int $id): void
    {
        // Scoped by recipient, so an id from the browser cannot reach another
        // member's notification.
        NotificationLog::where('id', $id)
            ->where('recipient_type', User::class)
            ->where('recipient_id', auth()->id())
            ->whereNull('read_at')
            ->update(['read_at' => now()]);
    }

    public function markAllRead(): void
    {
        NotificationLog::where('recipient_type', User::class)
            ->where('recipient_id', auth()->id())
            ->whereNull('read_at')
            ->update(['read_at' => now()]);
    }

    public function render()
    {
        $query = NotificationLog::where('recipient_type', User::class)
            ->where('recipient_id', auth()->id())
            ->orderByDesc('created_at');

        return view('livewire.portal.portal-notifications', [
            'logs' => $query->paginate(20),
            'unread' => (clone $query)->whereNull('read_at')->count(),
        ]);
    }
}
