<?php

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

class AddRazorpayIdempotencyIndexes extends Migration
{
    public function up()
    {
        $conn = Schema::connection('master');

        // Index on psp_reference for fast duplicate lookups during payment verification
        // Not UNIQUE because psp_reference is nullable and legacy rows may have nulls
        $conn->table('client_packages', function (Blueprint $table) {
            $table->index('psp_reference', 'idx_cp_psp_reference');
            $table->index('razorpay_subscription_id', 'idx_cp_rzp_sub_id');
        });

        // Index on gateway_subscription_id for fast order lookups from webhooks
        $conn->table('orders', function (Blueprint $table) {
            $table->index('gateway_subscription_id', 'idx_orders_gw_sub_id');
            $table->index('gateway_order_id', 'idx_orders_gw_order_id');
        });
    }

    public function down()
    {
        $conn = Schema::connection('master');

        $conn->table('client_packages', function (Blueprint $table) {
            $table->dropIndex('idx_cp_psp_reference');
            $table->dropIndex('idx_cp_rzp_sub_id');
        });

        $conn->table('orders', function (Blueprint $table) {
            $table->dropIndex('idx_orders_gw_sub_id');
            $table->dropIndex('idx_orders_gw_order_id');
        });
    }
}
