<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\PriceSyncService;
use Illuminate\Console\Command;
use Throwable;

class DataForSeoDispatchTasks extends Command
{
    protected $signature = 'dataforseo:dispatch-tasks
                            {--target= : ID o slug del target}
                            {--store= : Slug de la tienda}
                            {--product= : Slug del producto base}
                            {--limit=72 : Máximo de targets a despachar}
                            {--dry-run : Solo mostrar qué targets se despacharían}';

    protected $description = 'Despacha tareas async a DataForSEO Merchant Google Products para los targets activos.';

    public function handle(PriceSyncService $priceSyncService): int
    {
        try {
            $result = $priceSyncService->dispatchTasks($this->filters(), (bool) $this->option('dry-run'));

            if (($result['dry_run'] ?? false) === true) {
                $this->info('Dry run completado.');
                $this->line('Targets encontrados: '.(string) $result['targets_count']);
                $this->table(['Target slug'], array_map(static fn (string $slug): array => [$slug], $result['target_slugs'] ?? []));

                return self::SUCCESS;
            }

            if (($result['targets_count'] ?? 0) === 0) {
                $this->warn((string) ($result['message'] ?? 'No hubo targets para despachar.'));

                return self::SUCCESS;
            }

            $this->info('Despacho completado.');
            $this->table(['Run ID', 'Targets', 'Tasks enviadas', 'Errores'], [[
                (string) $result['run_id'],
                (string) $result['targets_count'],
                (string) $result['tasks_submitted'],
                (string) $result['error_count'],
            ]]);

            return ((int) ($result['error_count'] ?? 0)) > 0 ? self::FAILURE : self::SUCCESS;
        } catch (Throwable $exception) {
            $this->error('Falló el despacho a DataForSEO: '.$exception->getMessage());

            return self::FAILURE;
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function filters(): array
    {
        return [
            'target' => $this->option('target'),
            'store' => $this->option('store'),
            'product' => $this->option('product'),
            'limit' => (int) $this->option('limit'),
        ];
    }
}
