<?php

namespace App\Console\Commands;

use App\Serp\Exceptions\SerpProviderException;
use App\Serp\Operations\DataForSeoHealthService;
use Illuminate\Console\Command;
use Throwable;

class DataForSeoHealthCommand extends Command
{
    protected $signature = 'serp:dataforseo:health {--remote : Açık izinle ücretsiz hesap/bakiye doğrulaması} {--json}';

    protected $description = 'DataForSEO yapılandırmasını güvenli biçimde doğrular';

    public function handle(DataForSeoHealthService $health): int
    {
        try {
            $data = $health->validateConfig();
            if ($this->option('remote')) {
                $r = $health->remote();
                $data += ['remote' => 'ok', 'balance_micros' => $r->balanceMicros, 'status_code' => $r->statusCode, 'checked_at' => $r->checkedAt->format(DATE_ATOM)];
            } else {
                $data += ['remote' => 'not_requested'];
            }$this->option('json') ? $this->line(json_encode($data, JSON_THROW_ON_ERROR)) : $this->info('DataForSEO health: OK (uzak çağrı: '.$data['remote'].')');

            return self::SUCCESS;
        } catch (Throwable $e) {
            $safe = ['status' => 'failed', 'category' => $e instanceof SerpProviderException ? $e->safeCode() : 'configuration_invalid'];
            $this->option('json') ? $this->line(json_encode($safe)) : $this->error('DataForSEO health doğrulanamadı.');

            return self::FAILURE;
        }
    }
}
