<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Region;
use App\Models\Commune;
use App\Models\PostalCode;
use Illuminate\Support\Facades\Http;

class ImportChileData extends Command
{
    protected $signature = 'import:chile';
    protected $description = 'Importa regiones, comunas y códigos postales de Chile';

    public function handle()
    {
        $this->info("Importando regiones...");

        $regions = Http::get("https://apis.digital.gob.cl/dpa/regiones")->json();

        foreach ($regions as $region) {
            Region::updateOrCreate(
                ['external_id' => $region['codigo']],
                ['name' => $region['nombre']]
            );
        }

        $this->info("Importando comunas...");

        $communes = Http::get("https://apis.digital.gob.cl/dpa/comunas")->json();

        foreach ($communes as $comuna) {
            $region = Region::where('external_id', $comuna['codigo_padre'])->first();

            if (!$region) continue;

            Commune::updateOrCreate(
                ['external_id' => $comuna['codigo']],
                [
                    'name' => $comuna['nombre'],
                    'region_id' => $region->id
                ]
            );
        }

        $this->info("Importando códigos postales...");

        $postalData = json_decode(file_get_contents(storage_path('postal_codes_chile.json')), true);

        foreach ($postalData as $item) {
            $commune = Commune::where('name', $item['comuna'])->first();
            if (!$commune) continue;

            foreach ($item['codigos'] as $code) {
                PostalCode::updateOrCreate(
                    [
                        'commune_id' => $commune->id,
                        'postal_code' => $code
                    ]
                );
            }
        }

        $this->info("Importación finalizada.");
    }
}
