<?php

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

class CreatePaymentRoutingTables extends Migration
{
    /**
     * 运行迁移
     *
     * @return void
     */
    public function up()
    {
        // 创建路由规则表
        Schema::create('payment_routing_rules', function (Blueprint $table) {
            $table->id();
            $table->string('name')->comment('规则名称');
            $table->text('condition')->comment('规则条件');
            $table->string('gateway')->comment('支付网关');
            $table->integer('priority')->default(0)->comment('优先级');
            $table->string('status')->default('active')->comment('状态');
            $table->timestamps();
        });

        // 创建路由决策记录表
        Schema::create('payment_routing_decisions', function (Blueprint $table) {
            $table->id();
            $table->text('params')->comment('决策参数');
            $table->string('selected_gateway')->comment('选择的网关');
            $table->unsignedBigInteger('matched_rule_id')->nullable()->comment('匹配的规则ID');
            $table->timestamps();

            $table->foreign('matched_rule_id')->references('id')->on('payment_routing_rules')->onDelete('set null');
        });

        // 创建索引
        Schema::table('payment_routing_rules', function (Blueprint $table) {
            $table->index('priority');
            $table->index('status');
            $table->index('gateway');
        });

        Schema::table('payment_routing_decisions', function (Blueprint $table) {
            $table->index('selected_gateway');
            $table->index('matched_rule_id');
        });
    }

    /**
     * 回滚迁移
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('payment_routing_decisions');
        Schema::dropIfExists('payment_routing_rules');
    }
}
