<?php

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

/**
 * Scope the stock batch number to its tenant.
 *
 * The original table declared a global unique index on internal_batch_number,
 * which the tenancy backfill (2026_07_08_000002_add_tenant_id_to_owned_tables)
 * failed to swap for a per-tenant composite — every other owned table's unique
 * keys were converted there. Test instances share the physical tables, so a
 * "Sync from Live" clone of a batch-tracked tenant collided with the live rows
 * (SQLSTATE 23000: duplicate 'BATCH-...' on
 * stock_batches_internal_batch_number_unique). Batch numbers are per-tenant by
 * design (DocumentNumberService), so the composite is the correct invariant.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('stock_batches', function (Blueprint $table) {
            $table->dropUnique('stock_batches_internal_batch_number_unique');
            $table->unique(['tenant_id', 'internal_batch_number']);
        });
    }

    public function down(): void
    {
        Schema::table('stock_batches', function (Blueprint $table) {
            $table->dropUnique(['tenant_id', 'internal_batch_number']);
            $table->unique('internal_batch_number', 'stock_batches_internal_batch_number_unique');
        });
    }
};