<?php

namespace App\Console\Commands;

use App\Models\IntegrationSetting;
use App\Models\IntegrationSyncLog;
use App\Services\IntegrationOperationService;
use Illuminate\Console\Command;

class ProcessIntegrationOperations extends Command
{
    protected $signature = 'crm:process-integrations {--health}';
    protected $description = 'Retry outbound integration operations and check provider health';

    public function handle(IntegrationOperationService $operations): int
    {
        IntegrationSyncLog::withoutGlobalScopes()
            ->where('direction','outbound')->where('status','pending')
            ->where(fn($query)=>$query->whereNull('next_retry_at')->orWhere('next_retry_at','<=',now()))
            ->whereColumn('attempts','<','max_attempts')->orderBy('id')->limit(100)->get()
            ->each(fn($log)=>$operations->process($log));

        if($this->option('health')){
            IntegrationSetting::withoutGlobalScopes()->where('enabled',true)
                ->where(fn($query)=>$query->whereNull('last_health_checked_at')
                    ->orWhere('last_health_checked_at','<=',now()->subHour()))
                ->get()->each(fn($setting)=>$operations->health($setting));
        }
        return self::SUCCESS;
    }
}
