<?php

use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * 为 order_items 表添加 created_date 字段（冗余存储父订单创建时间）
     * 用于 hypertable 分区键，与 orders 表保持相同的分区策略
     */
    public function up(): void
    {
        Schema::table('order_items', function (Blueprint $table) {
            $table->timestampTz('created_date')
                ->after('platform_order_id')
                ->comment('订单创建时间（冗余存储，用于分区）');
        });

        // 从关联的 orders 表填充 created_date
        Schema::getConnection()->statement('
            UPDATE order_items
            SET created_date = orders.created_date
            FROM orders
            WHERE order_items.order_id = orders.id
        ');

        // 设置为非空（使用原生 SQL 避免 doctrine/dbal 依赖）
        Schema::getConnection()->statement('
            ALTER TABLE order_items ALTER COLUMN created_date SET NOT NULL
        ');

        // 添加索引
        Schema::table('order_items', function (Blueprint $table) {
            $table->index('created_date', 'order_items_created_date_idx');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('order_items', function (Blueprint $table) {
            $table->dropIndex('order_items_created_date_idx');
            $table->dropColumn('created_date');
        });
    }
};
