<?php

namespace App\Console\Commands;

use App\Models\PlatformConnection;
use App\Services\Integrations\Discovery\AccountDiscoveryService;
use Illuminate\Console\Command;

class DiscoverAccountsCommand extends Command
{
    protected $signature = 'dw:discover-accounts {connection? : Platform connection ID} {--platform= : google_ads, meta_ads, search_console, ga4} {--client= : Client ID} {--limit=50}';

    protected $description = 'API bağlantılarından erişilebilir reklam hesabı / Search Console mülkü / GA4 property listesini getirir.';

    public function handle(AccountDiscoveryService $discovery): int
    {
        $query = PlatformConnection::with(['client', 'secureCredential'])
            ->when($this->argument('connection'), fn ($q, $id) => $q->whereKey($id))
            ->when($this->option('platform'), fn ($q, $platform) => $q->where('platform', $platform))
            ->when($this->option('client'), fn ($q, $clientId) => $q->where('client_id', $clientId))
            ->orderBy('platform')
            ->orderBy('id');

        $connections = $query->get();

        if ($connections->isEmpty()) {
            $this->warn('Keşif yapılacak bağlantı bulunamadı.');
            return self::SUCCESS;
        }

        $limit = (int) $this->option('limit');

        foreach ($connections as $connection) {
            $this->newLine();
            $this->info("#{$connection->id} {$connection->connection_name} / {$connection->platform}");
            $result = $discovery->discover($connection, $limit);

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

            if (! empty($result->accounts)) {
                $this->table(
                    ['ID', 'Ad', 'Para Birimi', 'Zaman Dilimi', 'Resource'],
                    collect($result->accounts)->map(fn (array $account) => [
                        $account['account_id'] ?? '-',
                        $account['account_name'] ?? '-',
                        $account['currency_code'] ?? '-',
                        $account['timezone'] ?? '-',
                        $account['resource_name'] ?? '-',
                    ])->all()
                );
            }
        }

        return self::SUCCESS;
    }
}
