<?php

namespace Kylin\World\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class ImportRegionsCommand extends Command
{
    protected $signature = 'kylin:world:import {--country=CN : Country code to import}';
    protected $description = 'Import region data from National Bureau of Statistics';

    public function handle(): int
    {
        $country = $this->option('country');

        $this->info("Importing regions for country: {$country}");

        // 中国行政区划数据导入
        if ($country === 'CN') {
            $this->importChinaRegions();
        }

        $this->info('Region import completed.');
        return self::SUCCESS;
    }

    private function importChinaRegions(): void
    {
        $this->info('Importing China regions from NBS data...');

        $dataFile = __DIR__ . '/../../data/china_regions.json';

        if (!file_exists($dataFile)) {
            $this->error('China regions data file not found. Please download it first.');
            return;
        }

        $data = json_decode(file_get_contents($dataFile), true);
        $batch = [];

        foreach ($data as $item) {
            $batch[] = [
                'parent_id' => $item['parent_id'] ?? 0,
                'name' => $item['name'],
                'code' => $item['code'],
                'country_code' => 'CN',
                'level' => $item['level'],
                'sort' => $item['sort'] ?? 0,
                'created_at' => now(),
                'updated_at' => now(),
            ];

            if (count($batch) >= 500) {
                \DB::table('kylin_regions')->upsert($batch, ['code'], ['name', 'sort', 'updated_at']);
                $batch = [];
                $this->output->write('.');
            }
        }

        if (!empty($batch)) {
            \DB::table('kylin_regions')->upsert($batch, ['code'], ['name', 'sort', 'updated_at']);
        }

        $this->newLine();
    }
}
