<?php

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('pricing_rules', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->string('name_ar');
            $table->string('name')->nullable();
            $table->text('description_ar')->nullable();
            $table->string('rule_type', 30);
            $table->string('adjustment_type', 30);
            $table->bigInteger('adjustment_value');
            $table->jsonb('conditions')->default('{}');
            $table->string('target_type')->nullable();
            $table->unsignedBigInteger('target_id')->nullable();
            $table->foreignId('branch_id')->nullable()->constrained('branches');
            $table->integer('priority')->default(0);
            $table->boolean('is_stackable')->default(true);
            $table->integer('max_discount_percent')->nullable();
            $table->date('effective_from')->nullable();
            $table->date('effective_to')->nullable();
            $table->boolean('is_active')->default(true);
            $table->integer('usage_limit')->nullable();
            $table->integer('usage_count')->default(0);
            $table->foreignId('created_by')->constrained('users');
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();
            $table->softDeletes();

            $table->index(['academy_id', 'rule_type', 'is_active']);
            $table->index(['academy_id', 'target_type', 'target_id']);
            $table->index(['priority']);
            $table->index(['effective_from', 'effective_to']);
            $table->index(['branch_id', 'is_active']);
        });

        DB::statement("ALTER TABLE pricing_rules ADD CONSTRAINT pricing_rules_rule_type_check CHECK (rule_type IN ('age', 'membership_duration', 'family_size', 'sibling_order', 'classification', 'enrollment_timing', 'enrollment_volume', 'seasonal', 'gender', 'branch', 'day_time', 'loyalty', 'custom'))");

        DB::statement("ALTER TABLE pricing_rules ADD CONSTRAINT pricing_rules_adjustment_type_check CHECK (adjustment_type IN ('percentage_discount', 'fixed_discount', 'fixed_price', 'percentage_increase'))");
    }

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