<?php

namespace App\Console\Commands;

use App\Services\Operations\OperationCenterService;
use Illuminate\Console\Command;

class OperationDigestCommand extends Command
{
    protected $signature = 'dw:operations-digest {--readiness=} {--platform=}';

    protected $description = 'Ajans operasyon merkezi için müşteri durum özetini terminalde gösterir.';

    public function handle(OperationCenterService $operations): int
    {
        $data = $operations->dashboard([
            'readiness' => $this->option('readiness') ?: null,
            'platform' => $this->option('platform') ?: null,
        ]);

        $summary = $data['summary'];
        $this->info('DW Ads Reporter Operasyon Özeti');
        $this->line('Müşteri: '.$summary['clients_total']);
        $this->line('Hazır: '.$summary['ready'].' | Kontrol: '.$summary['warning'].' | Kritik: '.$summary['critical']);
        $this->line('İlk rapor bekleyen: '.$summary['needs_first_report']);
        $this->line('Açık uyarı: '.$summary['open_alerts'].' | API hata 24s: '.$summary['api_errors_24h'].' | Mail hata 24s: '.$summary['failed_mails_24h']);

        $rows = $data['clients']->map(function (array $card) {
            return [
                $card['client']->company_name,
                $card['readiness_label'],
                $card['connections_active'].'/'.$card['connections_total'],
                $card['avg_quality'] ?? '-',
                $card['open_alerts'],
                $card['active_schedules'],
                optional($card['last_report'])->created_at?->format('Y-m-d H:i') ?? '-',
                count($card['actions']),
            ];
        })->all();

        $this->table(['Müşteri', 'Durum', 'Bağlantı', 'Kalite', 'Uyarı', 'Plan', 'Son Rapor', 'Aksiyon'], $rows);

        return self::SUCCESS;
    }
}
