<?php

namespace App\Console\Commands;

use App\Models\PlatformConnection;
use App\Services\Integrations\Preview\DataPreviewService;
use Illuminate\Console\Command;

class PreviewConnectionDataCommand extends Command
{
    protected $signature = 'dw:preview-data {connection : Platform connection ID} {--from=} {--to=} {--limit=10}';

    protected $description = 'API bağlantısından snapshot kaydetmeden canlı veri önizlemesi alır.';

    public function handle(DataPreviewService $preview): int
    {
        $connection = PlatformConnection::with(['client', 'secureCredential'])->find((int) $this->argument('connection'));
        if (! $connection) {
            $this->error('Bağlantı bulunamadı.');
            return self::FAILURE;
        }

        $from = $this->option('from') ?: now()->subDays(7)->toDateString();
        $to = $this->option('to') ?: now()->subDay()->toDateString();
        $limit = (int) $this->option('limit');

        $result = $preview->preview($connection, $from, $to, $limit);

        $this->{$result->ok ? 'info' : 'error'}($result->message);
        if ($result->error) {
            $this->line($result->error);
        }

        if (! empty($result->totals)) {
            $this->newLine();
            $this->info('Toplamlar');
            $this->table(['Metrik', 'Değer'], collect($result->totals)->map(fn ($value, $key) => [$key, $value])->values()->all());
        }

        if (! empty($result->rows)) {
            $this->newLine();
            $this->info('İlk satırlar');
            $headers = array_keys($result->rows[0]);
            $this->table($headers, collect($result->rows)->map(fn ($row) => collect($headers)->map(fn ($key) => $row[$key] ?? null)->all())->all());
        }

        if (! empty($result->diagnostics)) {
            $this->newLine();
            $this->info('Tanılama');
            $this->line(json_encode($result->diagnostics, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        }

        return $result->ok ? self::SUCCESS : self::FAILURE;
    }
}
