<?php

use App\Models\JenjangJabatan;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('jenjang_jabatan', function (Blueprint $table) {
            $table->id();
            $table->string('kode')->unique();
            $table->string('nama_jenjang');
            $table->string('kategori');
            $table->string('golongan_min');
            $table->string('golongan_max');
            $table->unsignedTinyInteger('usia_pensiun');
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();
        });

        foreach (JenjangJabatan::DEFAULTS as $jenjang) {
            DB::table('jenjang_jabatan')->insert([
                ...$jenjang,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        Schema::table('jabatan_fungsional', function (Blueprint $table) {
            $table->foreignId('jenjang_jabatan_id')
                ->nullable()
                ->after('nama_jabatan')
                ->constrained('jenjang_jabatan')
                ->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('jabatan_fungsional', function (Blueprint $table) {
            $table->dropConstrainedForeignId('jenjang_jabatan_id');
        });

        Schema::dropIfExists('jenjang_jabatan');
    }
};
