<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class BinderByteMappingSeeder extends Seeder
{
    public function run()
    {
        $apiKey = env('BINDERBYTE_API_KEY');

        if (! $apiKey) {
            $this->command->error('API Key BinderByte belum diset di .env!');

            return;
        }

        // Kita ambil semua kota di database lokal
        // Chunking biar gak berat (ambil per 50 data)
        DB::table('regencies')->orderBy('id')->chunk(50, function ($cities) use ($apiKey) {
            foreach ($cities as $city) {
                // Bersihkan nama kota biar gampang dicari (Hapus "KABUPATEN" / "KOTA")
                // Contoh: "KABUPATEN BOGOR" -> "Bogor"
                $cleanName = str_replace(['KABUPATEN ', 'KOTA '], '', $city->name);

                // Cari ke API BinderByte
                $response = Http::get('https://api.binderbyte.com/v1/area', [
                    'api_key' => $apiKey,
                    'search' => $cleanName,
                ]);

                if ($response->successful()) {
                    $data = $response->json();
                    if (! empty($data['data'])) {
                        // Ambil hasil pertama yang paling cocok
                        $found = $data['data'][0];

                        // Update database lokal
                        DB::table('regencies')
                            ->where('id', $city->id)
                            ->update(['binderbyte_code' => $found['id']]); // ID BinderByte itu string/code

                        echo '.'; // Indikator progress
                    }
                }
            }
        });

        echo "\n Mapping Selesai!";
    }
}
