<?php

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

class CreatePaymentWebhooksTable extends Migration
{
    /**
     * 运行迁移
     *
     * @return void
     */
    public function up()
    {
        // 创建Webhook表
        Schema::create('payment_webhooks', function (Blueprint $table) {
            $table->id();
            $table->string('event')->comment('事件类型');
            $table->string('url')->comment('Webhook地址');
            $table->text('headers')->nullable()->comment('请求头');
            $table->text('options')->nullable()->comment('选项');
            $table->string('status')->default('active')->comment('状态');
            $table->timestamps();
        });

        // 创建Webhook事件表
        Schema::create('payment_webhook_events', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('webhook_id')->comment('Webhook ID');
            $table->string('event')->comment('事件类型');
            $table->text('payload')->comment('事件数据');
            $table->string('status')->default('pending')->comment('状态');
            $table->text('response')->nullable()->comment('响应数据');
            $table->text('error')->nullable()->comment('错误信息');
            $table->integer('attempts')->default(0)->comment('尝试次数');
            $table->timestamps();

            $table->foreign('webhook_id')->references('id')->on('payment_webhooks')->onDelete('cascade');
        });

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

        Schema::table('payment_webhook_events', function (Blueprint $table) {
            $table->index('webhook_id');
            $table->index('event');
            $table->index('status');
        });
    }

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