<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Business\MasterData\DberpChinaRegionImportService;
use Illuminate\Console\Command;
use Throwable;

class ImportDberpChinaRegionsCommand extends Command
{
    protected $signature = 'dberp:regions:import-china
                            {--reactivate-disabled : 对仍在导入范围内的、此前被人工停用的地区恢复为启用}';

    protected $description = '从内置 JSON 导入省、市、区县三级内地地区主数据（幂等，不含国家根节点）';

    public function handle(DberpChinaRegionImportService $service): int
    {
        $this->components->info('开始导入省市区县…');

        try {
            $summary = $service->import((bool) $this->option('reactivate-disabled'));
        } catch (Throwable $throwable) {
            $this->components->error('导入失败：'.$throwable->getMessage());

            return self::FAILURE;
        }

        $this->line('说明：初始化、重复执行、补录更新走同一套幂等逻辑；不写「中国」根节点，省为顶级。');
        $this->line('国家代码：'.$summary['country_code'].'（用于归属与筛选；展示名：'.$summary['country_name'].'）');
        $this->line('数据来源：'.$summary['source']);
        $this->line('数据文件：'.$summary['data_file']);
        $this->line('覆盖规则：名称、层级、父子关系、完整路径、排序按数据源修正；人工简称默认保留');
        $this->line('停用规则：默认保留人工停用；仅传入 --reactivate-disabled 时才把同步范围内已停用的行重新启用');
        $this->line('总记录数：'.(string) $summary['total']);
        $this->line('新增：'.(string) $summary['created']);
        $this->line('更新：'.(string) $summary['updated']);

        if (isset($summary['reactivated']) && (int) $summary['reactivated'] > 0) {
            $this->line('重新启用：'.(string) $summary['reactivated']);
        }

        $this->components->info('省市区县导入完成。');

        return self::SUCCESS;
    }
}
