<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;

class RtlhSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 1. Ambil semua file JSON dari folder public/maps
        $path = public_path('maps');
        
        // Pastikan folder ada
        if (!File::exists($path)) {
            $this->command->error("Folder public/maps tidak ditemukan!");
            return;
        }

        $files = File::files($path);
        
        $this->command->info("Ditemukan " . count($files) . " file map. Mulai import...");

        // Kosongkan tabel dulu agar bersih saat re-seed
        DB::table('region_stats')->truncate();

        DB::beginTransaction();
        try {

            foreach ($files as $file) {
                $filename = $file->getFilename();
                $this->command->warn("Processing: " . $filename);

                $jsonContent = File::get($file->getPathname());
                $data = json_decode($jsonContent, true);

                if (!isset($data['features'])) {
                    $this->command->error("Skip $filename: Format tidak valid (tidak ada features).");
                    continue;
                }

                $batchData = [];
                foreach ($data['features'] as $feature) {
                    $attrs = $feature['attributes'] ?? [];

                    // Mapping kolom
                    // WADMKK -> kabupaten
                    // WADMKC -> kecamatan
                    // WADMKD -> kelurahan
                    // RTLH_KD -> jumlah_rtlh

                    $batchData[] = [
                        'kabupaten'   => $attrs['WADMKK'] ?? 'Unknown',
                        'kecamatan'   => $attrs['WADMKC'] ?? 'Unknown',
                        'kelurahan'   => $attrs['WADMKD'] ?? 'Unknown',
                        'jumlah_rtlh' => isset($attrs['RTLH_KD']) ? (int)$attrs['RTLH_KD'] : 0,
                        'file_source' => $filename,
                        'created_at'  => Carbon::now(),
                        'updated_at'  => Carbon::now(),
                    ];

                    // Insert per batch jika terlalu banyak untuk menghindari memory limit (opsional, tapi good practice)
                    if (count($batchData) >= 500) {
                        DB::table('region_stats')->insert($batchData);
                        $batchData = [];
                    }
                }

                // Insert sisa data
                if (!empty($batchData)) {
                    DB::table('region_stats')->insert($batchData);
                }
            }
            
            DB::commit();
            $this->command->info("Sukses! Semua data berhasil diimport ke tabel region_stats.");

        } catch (\Exception $e) {
            DB::rollBack();
            $this->command->error("Terjadi error: " . $e->getMessage());
        }
    }
}
