<?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
{
    /**
     * Guarantee one buyer per position per item. Positions were previously
     * assigned with max(position)+1 outside a transaction, so concurrent
     * commits could produce duplicates — renumber each item's queue by
     * join order before adding the constraint.
     */
    public function up(): void
    {
        $entries = DB::table('buy_queue')
            ->orderBy('item_id')
            ->orderBy('position')
            ->orderBy('created_at')
            ->orderBy('id')
            ->get(['id', 'item_id']);

        $position = 0;
        $currentItem = null;
        foreach ($entries as $entry) {
            if ($entry->item_id !== $currentItem) {
                $currentItem = $entry->item_id;
                $position = 0;
            }
            $position++;
            DB::table('buy_queue')->where('id', $entry->id)->update(['position' => $position]);
        }

        Schema::table('buy_queue', function (Blueprint $table) {
            $table->unique(['item_id', 'position']);
        });
    }

    public function down(): void
    {
        Schema::table('buy_queue', function (Blueprint $table) {
            $table->dropUnique(['item_id', 'position']);
        });
    }
};
