<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class PoliSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->ensureTableAndColumns();

        DB::table('poli')->truncate();

        foreach (array_chunk($this->jsonData(), 500) as $chunk) {
            DB::table('poli')->insert($chunk);
        }

        $this->resetAutoIncrement();
    }

    private function ensureTableAndColumns(): void
    {
        if (!Schema::hasTable('poli')) {
            Schema::create('poli', function (Blueprint $table) {
                $table->id();
                $table->string('poli', 250)->nullable();
                $table->string('subpoli', 250)->nullable();
                $table->string('subsubpoli', 250)->nullable();
                $table->string('modaliti', 150)->nullable();
                $table->string('kelompok', 150)->nullable();
                $table->string('modaliti2', 150)->nullable();
                $table->timestamp('created_at')->useCurrent();
                $table->timestamp('updated_at')->useCurrent();
            });

            return;
        }

        Schema::table('poli', function (Blueprint $table) {
            if (!Schema::hasColumn('poli', 'poli')) {
                $table->string('poli', 250)->nullable();
            }

            if (!Schema::hasColumn('poli', 'subpoli')) {
                $table->string('subpoli', 250)->nullable();
            }

            if (!Schema::hasColumn('poli', 'subsubpoli')) {
                $table->string('subsubpoli', 250)->nullable();
            }

            if (!Schema::hasColumn('poli', 'modaliti')) {
                $table->string('modaliti', 150)->nullable();
            }

            if (!Schema::hasColumn('poli', 'kelompok')) {
                $table->string('kelompok', 150)->nullable();
            }

            if (!Schema::hasColumn('poli', 'modaliti2')) {
                $table->string('modaliti2', 150)->nullable();
            }

            if (!Schema::hasColumn('poli', 'created_at')) {
                $table->timestamp('created_at')->useCurrent();
            }

            if (!Schema::hasColumn('poli', 'updated_at')) {
                $table->timestamp('updated_at')->useCurrent();
            }
        });
    }

    private function jsonData(): array
    {
        $path = database_path('seeders/data/poli.json');
        $json = file_get_contents($path);

        if ($json === false) {
            throw new \RuntimeException("Gagal membuka file seeder poli: {$path}");
        }

        $data = json_decode($json, true);

        if (!is_array($data)) {
            throw new \RuntimeException("Format JSON seeder poli tidak valid: {$path}");
        }

        return $data;
    }

    private function resetAutoIncrement(): void
    {
        $driver = DB::getDriverName();

        if ($driver === 'pgsql') {
            DB::statement("
                SELECT setval(
                    pg_get_serial_sequence('poli', 'id'),
                    (SELECT COALESCE(MAX(id), 1) FROM poli),
                    (SELECT COUNT(*) > 0 FROM poli)
                )
            ");

            return;
        }

        if ($driver === 'mysql') {
            $nextId = ((int) DB::table('poli')->max('id')) + 1;
            DB::statement("ALTER TABLE poli AUTO_INCREMENT = {$nextId}");
        }
    }
}
