<?php

declare(strict_types=1);

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $connection = Schema::getConnection();

        // 将 platform_product_id 改为可空
        $connection->statement('ALTER TABLE skus_mapping ALTER COLUMN platform_product_id DROP NOT NULL');

        // 删除原有唯一约束（CONSTRAINT + INDEX 二选一，兼容两种形式）
        $connection->statement('ALTER TABLE skus_mapping DROP CONSTRAINT IF EXISTS uk_platform_product');
        $connection->statement('DROP INDEX IF EXISTS uk_platform_product');
        // 创建部分唯一索引（NULL 值不参与唯一性判断）
        $connection->statement(
            'CREATE UNIQUE INDEX uk_platform_product ON skus_mapping (platform_id, platform_product_id) WHERE platform_product_id IS NOT NULL'
        );
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $connection = Schema::getConnection();

        $connection->statement('DROP INDEX IF EXISTS uk_platform_product');
        $connection->statement(
            'CREATE UNIQUE INDEX uk_platform_product ON skus_mapping (platform_id, platform_product_id)'
        );

        // 恢复 NOT NULL（需确保无 NULL 数据）
        $connection->statement('ALTER TABLE skus_mapping ALTER COLUMN platform_product_id SET NOT NULL');
    }
};
