<?php

namespace App\Console\Commands;

use App\Services\Integrations\Sdk\ApiSdkStatusService;
use Illuminate\Console\Command;

class CheckApiSdkCommand extends Command
{
    protected $signature = 'dw:check-api-sdks {--json : JSON çıktı ver}';
    protected $description = 'Google Ads, Meta, Google API Client ve GA4 SDK kurulum durumunu kontrol eder.';

    public function handle(ApiSdkStatusService $status): int
    {
        $payload = [
            'summary' => $status->summary(),
            'packages' => $status->packages(),
            'extensions' => $status->extensions(),
            'commands' => $status->installCommands(),
            'warnings' => $status->warnings(),
        ];

        if ($this->option('json')) {
            $this->line(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            return self::SUCCESS;
        }

        $this->info('DW Ads Reporter API SDK Kontrolü');
        $this->line('');

        $this->table(['Paket', 'Composer', 'Durum', 'Not'], collect($payload['packages'])->map(fn ($item) => [
            $item['name'],
            $item['package'],
            $item['status'] ? 'KURULU' : 'EKSİK',
            $item['notes'],
        ])->all());

        $this->table(['Extension', 'Durum', 'Zorunlu', 'Not'], collect($payload['extensions'])->map(fn ($item) => [
            $item['extension'],
            $item['status'] ? 'AKTİF' : 'PASİF',
            $item['required'] ? 'Evet' : 'Hayır',
            $item['notes'],
        ])->all());

        $this->line('Kurulum komutu:');
        $this->warn($payload['commands']['all']);
        $this->line($payload['commands']['clear']);

        foreach ($payload['warnings'] as $warning) {
            $this->warn($warning);
        }

        return $payload['summary']['extension_errors'] > 0 ? self::FAILURE : self::SUCCESS;
    }
}
