<?php

namespace App\Jobs;

use App\Enums\NotificationSeverityEnum;
use App\Enums\NotificationTypeEnum;
use App\Models\Feed;
use App\Models\Notification;
use App\Models\Setting;
use App\Services\Notification\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class CheckFeedStalenessJob implements ShouldQueue
{
    use Queueable;

    public function handle(NotificationService $notificationService): void
    {
        $thresholdHours = Setting::getFeedStalenessThreshold();

        if ($thresholdHours === 0) {
            return;
        }

        $staleFeeds = Feed::stale($thresholdHours)->get();

        foreach ($staleFeeds as $feed) {
            $alreadyNotified = Notification::query()
                ->where('type', NotificationTypeEnum::FEED_STALE)
                ->where('notifiable_type', $feed->getMorphClass())
                ->where('notifiable_id', $feed->getKey())
                ->unread()
                ->exists();

            if ($alreadyNotified) {
                continue;
            }

            $notificationService->send(
                type: NotificationTypeEnum::FEED_STALE,
                severity: NotificationSeverityEnum::WARNING,
                title: "Feed \"{$feed->name}\" is stale",
                message: $feed->last_fetched_at
                    ? "Last fetched {$feed->last_fetched_at->diffForHumans()}. Threshold is {$thresholdHours} hours."
                    : "This feed has never been fetched. Threshold is {$thresholdHours} hours.",
                notifiable: $feed,
            );
        }
    }
}
