<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\Countries\CountrySyncService;
use Illuminate\Console\Command;
use Throwable;

final class SyncCountriesCommand extends Command
{
    protected $signature = 'skinbase:sync-countries
        {--deactivate-missing : Mark countries missing from the source as inactive}
        {--no-fallback : Fail instead of using the local fallback dataset when remote fetch fails}';

    protected $description = 'Synchronize ISO 3166 country metadata into the local countries table.';

    public function __construct(
        private readonly CountrySyncService $countrySyncService,
    ) {
        parent::__construct();
    }

    public function handle(): int
    {
        try {
            $summary = $this->countrySyncService->sync(
                allowFallback: ! (bool) $this->option('no-fallback'),
                deactivateMissing: (bool) $this->option('deactivate-missing') ? true : null,
            );
        } catch (Throwable $exception) {
            $this->error($exception->getMessage());

            return self::FAILURE;
        }

        $this->info('Countries synchronized successfully.');
        $this->line('Source: '.($summary['source'] ?? 'unknown'));
        $this->line('Fetched: '.(int) ($summary['total_fetched'] ?? 0));
        $this->line('Inserted: '.(int) ($summary['inserted'] ?? 0));
        $this->line('Updated: '.(int) ($summary['updated'] ?? 0));
        $this->line('Skipped: '.(int) ($summary['skipped'] ?? 0));
        $this->line('Invalid: '.(int) ($summary['invalid'] ?? 0));
        $this->line('Deactivated: '.(int) ($summary['deactivated'] ?? 0));
        $this->line('Backfilled users: '.(int) ($summary['backfilled_users'] ?? 0));

        return self::SUCCESS;
    }
}
