<?php

namespace Database\Seeders;

use App\Models\Kecamatan;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\Kabupaten;

class KecamatanTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $kabupatens = Kabupaten::all();

        foreach ($kabupatens as $kabupaten) {
            $kabId = substr($kabupaten->KabupatenId, 0, 2) . '.' .
                    substr($kabupaten->KabupatenId, 2, 2);

            $response = Http::get("https://api-wilayah.dinaslhdki.id/api/kecamatan/search?kab={$kabId}");

            foreach ($response->json() as $kecamatan) {
                $cleanId = str_replace('.', '', $kecamatan['id']);

                Kecamatan::create([
                    'KecamatanId' => $cleanId,
                    'KabupatenId' => $kabupaten->KabupatenId,
                    'NamaKecamatan' => $kecamatan['data']
                ]);

                // Log the seeding process
                Log::info('Seeding kecamatan: ', [
                    'KecamatanId' => $cleanId,
                    'KabupatenId' => $kabupaten->KabupatenId,
                    'NamaKecamatan' => $kecamatan['data']
                ]);
            }
        }
    }
}
