<?php

namespace Database\Seeders;

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

class KelurahanTableSeeder extends Seeder
{
    public function run(): void
    {
        $kecamatans = Kecamatan::all();

        foreach ($kecamatans as $kecamatan) {
            $kecId = substr($kecamatan->KecamatanId, 0, 2) . '.' .
                    substr($kecamatan->KecamatanId, 2, 2) . '.' .
                    substr($kecamatan->KecamatanId, 4, 2);

            $response = Http::get("https://api-wilayah.dinaslhdki.id/api/kelurahan/search?kec={$kecId}");

            foreach ($response->json() as $kelurahan) {
                $cleanId = str_replace('.', '', $kelurahan['id']);
                $cleanName = str_replace("\n", ' ', $kelurahan['data']);

                Kelurahan::create([
                    'KelurahanId' => $cleanId,
                    'KecamatanId' => $kecamatan->KecamatanId,
                    'NamaKelurahan' => $cleanName
                ]);

                Log::info('Seeding kelurahan: ', [
                    'KelurahanId' => $cleanId,
                    'KecamatanId' => $kecamatan->KecamatanId,
                    'NamaKelurahan' => $cleanName
                ]);
            }
        }
    }
}
