<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Step 1: Remove duplicate subscriptions (keep newest by ID)
        $this->resolveDuplicateSubscriptions();

        // Step 2: Remove duplicate transactions (keep newest by ID)
        $this->resolveDuplicateTransactions();

        // Step 3: Convert indexes to unique constraints
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropIndex(['subscription_id']);
            $table->unique('subscription_id');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->dropIndex(['external_transaction_id']);
            $table->unique('external_transaction_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropUnique(['subscription_id']);
            $table->index('subscription_id');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->dropUnique(['external_transaction_id']);
            $table->index('external_transaction_id');
        });
    }

    /**
     * Remove duplicate subscriptions, keeping the newest one by ID.
     */
    private function resolveDuplicateSubscriptions(): void
    {
        // MySQL requires wrapping subquery in derived table to avoid error 1093
        DB::statement('
            DELETE FROM subscriptions WHERE id NOT IN (
                SELECT id FROM (
                    SELECT MAX(id) as id FROM subscriptions
                    WHERE subscription_id IS NOT NULL
                    GROUP BY subscription_id
                ) AS temp
            ) AND subscription_id IS NOT NULL
        ');
    }

    /**
     * Remove duplicate transactions, keeping the newest one by ID.
     */
    private function resolveDuplicateTransactions(): void
    {
        // MySQL requires wrapping subquery in derived table to avoid error 1093
        DB::statement('
            DELETE FROM transactions WHERE id NOT IN (
                SELECT id FROM (
                    SELECT MAX(id) as id FROM transactions
                    WHERE external_transaction_id IS NOT NULL
                    GROUP BY external_transaction_id
                ) AS temp
            ) AND external_transaction_id IS NOT NULL
        ');
    }
};
