<?php

declare(strict_types=1);

namespace App\Filament\Widgets;

use App\Filament\Pages\HostSystemUpdateCenterPage;
use App\Models\DberpSystemUpdateNotice;
use App\Services\DberpPermissionService;
use App\Services\DberpSystemUpdateNoticeService;
use Filament\Notifications\Notification;
use Filament\Widgets\Widget;
use Illuminate\Support\Facades\Auth;

class SystemUpdateNoticeWorkbenchWidget extends Widget
{
    protected static bool $isLazy = false;

    protected string $view = 'filament.widgets.system-update-notice-workbench-widget';

    protected int|string|array $columnSpan = 'full';

    public static function canView(): bool
    {
        return app(DberpPermissionService::class)->allows(
            Auth::user(),
            DberpPermissionService::VIEW_HOST_SYSTEM_UPDATE,
        );
    }

    public function notice(): ?DberpSystemUpdateNotice
    {
        return app(DberpSystemUpdateNoticeService::class)->latestActiveNoticeFor(Auth::user());
    }

    public function panelData(): ?array
    {
        return app(DberpSystemUpdateNoticeService::class)->panelViewDataFor(Auth::user());
    }

    public function updateCenterUrl(): string
    {
        return HostSystemUpdateCenterPage::getUrl(panel: 'admin');
    }

    public function markSystemUpdateNoticeAsRead(): void
    {
        $notice = $this->notice();

        if ($notice === null) {
            return;
        }

        $user = Auth::user();

        if ($user === null) {
            return;
        }

        if (! app(DberpSystemUpdateNoticeService::class)->markAsRead($user, (int) $notice->getKey())) {
            return;
        }

        Notification::make()
            ->success()
            ->title(__('dberp.system_update_notice.messages.marked_read'))
            ->send();
    }

    public function dismissSystemUpdateNotice(): void
    {
        $notice = $this->notice();

        if ($notice === null) {
            return;
        }

        $user = Auth::user();

        if ($user === null) {
            return;
        }

        if (! app(DberpSystemUpdateNoticeService::class)->dismiss($user, (int) $notice->getKey())) {
            return;
        }

        Notification::make()
            ->success()
            ->title(__('dberp.system_update_notice.messages.dismissed'))
            ->send();
    }
}
