<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('m_range_dois', function (Blueprint $table) {
            $table->id();
            $table->string('name', 50);
            $table->decimal('min_days', 8, 2);
            $table->decimal('max_days', 8, 2);
            $table->string('color_code', 7); // Hex color code #FFFFFF
            $table->text('description')->nullable();
            $table->boolean('is_active')->default(true);
            $table->boolean('delete_flag')->default(false);
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();

            // Indexes
            $table->index(['min_days', 'max_days', 'delete_flag']);
            $table->index(['is_active', 'delete_flag']);
            $table->index(['name', 'delete_flag']);

            // Check constraint untuk memastikan max_days >= min_days
            // Akan ditambahkan via raw SQL setelah tabel dibuat

            // Foreign key constraints (jika tabel users sudah ada)
            // $table->foreign('created_by')->references('id')->on('users');
            // $table->foreign('updated_by')->references('id')->on('users');
        });

        // Tambahkan check constraint untuk PostgreSQL
        DB::statement('ALTER TABLE m_range_dois ADD CONSTRAINT check_range_dois_days CHECK (max_days >= min_days)');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('m_range_dois');
    }
};
