<?php

namespace App\Console\Commands;

use App\Jobs\SyncPlatformConnectionJob;
use App\Models\PlatformConnection;
use App\Services\Sync\DateRangeResolver;
use App\Services\Sync\PlatformSyncManager;
use Illuminate\Console\Command;

class SyncPlatformDataCommand extends Command
{
    protected $signature = 'dw:sync-platform {connection_id? : Tek bağlantı ID} {--platform=} {--client_id=} {--from=} {--to=} {--queue : Queue ile çalıştır}';

    protected $description = 'DW Ads Reporter platform bağlantılarından günlük snapshot verisi çeker.';

    public function handle(DateRangeResolver $rangeResolver, PlatformSyncManager $syncManager): int
    {
        [$from, $to] = $rangeResolver->resolve($this->option('from'), $this->option('to'));

        $query = PlatformConnection::with('secureCredential')->whereIn('status', ['active', 'draft', 'error']);

        if ($this->argument('connection_id')) {
            $query->whereKey((int) $this->argument('connection_id'));
        }
        if ($this->option('platform')) {
            $query->where('platform', $this->option('platform'));
        }
        if ($this->option('client_id')) {
            $query->where('client_id', (int) $this->option('client_id'));
        }

        $connections = $query->get();
        if ($connections->isEmpty()) {
            $this->warn('Senkronize edilecek bağlantı bulunamadı.');
            return self::SUCCESS;
        }

        foreach ($connections as $connection) {
            if ($this->option('queue')) {
                SyncPlatformConnectionJob::dispatch($connection->id, $from, $to);
                $this->info("Queue eklendi: #{$connection->id} {$connection->connection_name} ({$from} - {$to})");
                continue;
            }

            $this->line("Çalışıyor: #{$connection->id} {$connection->connection_name} / {$connection->platform}");
            $result = $syncManager->syncConnection($connection, $from, $to);
            $result->ok ? $this->info($result->message.' '.json_encode($result->counts, JSON_UNESCAPED_UNICODE)) : $this->error($result->error);
        }

        return self::SUCCESS;
    }
}
