<?php

namespace App\Console\Commands;

use App\Enums\KeywordStatus;
use App\Enums\UserStatus;
use App\Models\Keyword;
use App\Serp\Operations\ActivationManager;
use App\Services\NextCheckAtCalculator;
use App\Services\SerpCheckCreator;
use Illuminate\Console\Command;

class DispatchDueSerpChecks extends Command
{
    protected $signature = 'serp:dispatch-due';

    protected $description = 'Due SERP kontrollerini kuyruğa alır';

    public function handle(SerpCheckCreator $creator, NextCheckAtCalculator $next, ActivationManager $activation): int
    {
        if (! config('serp.enabled') || ! config('serp.provider') || (config('serp.provider') === 'dataforseo' && ! $activation->allowsNormal())) {
            return self::SUCCESS;
        }Keyword::query()->with('project.user')->where('tracking_enabled', true)->where('status', KeywordStatus::Active)->where('next_check_at', '<=', now())->whereHas('project.user', fn ($q) => $q->where('status', UserStatus::Active))->whereDoesntHave('serpChecks', fn ($q) => $q->whereIn('status', ['pending', 'running']))->chunkById(100, function ($keywords) use ($creator, $next) {
            foreach ($keywords as $k) {
                try {
                    $creator->create($k->project->user, $k, true, 'scheduled');
                    $k->forceFill(['last_queued_at' => now(), 'next_check_at' => $next->calculate($k->check_frequency)])->save();
                } catch (\Throwable) {
                }
            }
        });

        return self::SUCCESS;
    }
}
