<?php

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

/**
 * PRC-1143 — konsolide şema: `invoice_billing_rules` tablosunun TAM tanımı (tek dosya).
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('invoice_billing_rules', function (Blueprint $t) {
            $t->id();
            $t->string('name', 120);
            $t->integer('priority')->default(0);
            $t->boolean('is_active')->default(1);
            $t->boolean('is_fallback')->default(0);
            $t->json('events');
            $t->json('conditions');
            $t->enum('action', ['dispatch','skip'])->default('dispatch');
            $t->unsignedBigInteger('billing_module_id')->nullable();
            $t->unsignedInteger('dispatch_delay_days')->default(0);
            $t->timestamp('created_at')->nullable();
            $t->timestamp('updated_at')->nullable();
            $t->timestamp('deleted_at')->nullable();
            $t->index('billing_module_id', 'invoice_billing_rules_billing_module_id_foreign');
            $t->index('is_active', 'invoice_billing_rules_is_active_index');
            $t->index(['is_active', 'priority'], 'invoice_billing_rules_is_active_priority_index');
            $t->index('is_fallback', 'invoice_billing_rules_is_fallback_index');
            $t->index('priority', 'invoice_billing_rules_priority_index');
            $t->foreign('billing_module_id', 'invoice_billing_rules_billing_module_id_foreign')->references('id')->on('invoice_billings')->onDelete('set null');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('invoice_billing_rules');
    }
};
