<?php

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

class CreatePaymentBatchOperationsTable extends Migration
{
    /**
     * 运行迁移
     *
     * @return void
     */
    public function up()
    {
        // 创建批量操作表
        Schema::create('payment_batch_operations', function (Blueprint $table) {
            $table->id();
            $table->string('type')->comment('操作类型');
            $table->integer('total_count')->comment('总数量');
            $table->integer('success_count')->default(0)->comment('成功数量');
            $table->integer('failed_count')->default(0)->comment('失败数量');
            $table->string('status')->default('pending')->comment('状态');
            $table->text('options')->nullable()->comment('选项');
            $table->text('result')->nullable()->comment('结果');
            $table->text('error')->nullable()->comment('错误信息');
            $table->timestamp('completed_at')->nullable()->comment('完成时间');
            $table->timestamps();
        });

        // 创建批量操作项表
        Schema::create('payment_batch_operation_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('batch_id')->comment('批量操作ID');
            $table->string('item_type')->comment('项目类型');
            $table->unsignedBigInteger('item_id')->nullable()->comment('项目ID');
            $table->string('status')->comment('状态');
            $table->text('payload')->comment('数据');
            $table->text('result')->nullable()->comment('结果');
            $table->text('error')->nullable()->comment('错误信息');
            $table->timestamps();

            $table->foreign('batch_id')->references('id')->on('payment_batch_operations')->onDelete('cascade');
        });

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

        Schema::table('payment_batch_operation_items', function (Blueprint $table) {
            $table->index('batch_id');
            $table->index('item_type');
            $table->index('item_id');
            $table->index('status');
        });
    }

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