<?php

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

/**
 * 2026_08_23_000001_add_is_batch_tracked_to_products.php added the column
 * with `default(false)` and no backfill, even though its own doc comment
 * calls ON "legacy behaviour for every product" — every product that already
 * existed was tracked per-batch (a lot picker, FEFO/FIFO selection, and the
 * `inventory_batches.override` gate on every sale) simply because that was
 * the only behaviour that existed before this switch did. Left at the
 * column's default, that migration silently flipped every one of those
 * products to the new unified-pool mode: no lot picker, no override check,
 * stock and price sourced from whichever lot happens to be "active" instead
 * of the one the operator or FEFO/FIFO order would have picked.
 *
 * This repairs that for every product that existed at the moment the column
 * was added — new products created afterward already carry an explicit
 * operator choice from ProductResource's toggle (default off, but always
 * sent), so nothing here should touch them. There is no reliable timestamp
 * to distinguish the two groups (a product created in the same request the
 * column was added would look identical), so this targets every row that is
 * still sitting on the untouched default: `is_batch_tracked = false`. A
 * product genuinely created as unified-pool after the switch shipped is
 * indistinguishable from one this migration is fixing — but the moment this
 * runs (immediately after 2026_08_23_000001 in the same deploy), zero such
 * rows can exist yet, so the set is exactly the legacy backfill target.
 */
return new class extends Migration
{
    private const BACKFILL_LOG = 'products_batch_tracked_backfill';

    public function up(): void
    {
        // Re-running up() (fresh deploy re-try, or a test exercising it after
        // the suite already migrated) must start from a clean slate — the
        // previous run's log belongs to that run's ids.
        Schema::dropIfExists(self::BACKFILL_LOG);

        $ids = DB::table('products')
            ->where('is_batch_tracked', false)
            ->pluck('id');

        DB::table('products')
            ->where('is_batch_tracked', false)
            ->update(['is_batch_tracked' => true]);

        // Log exactly which rows were touched so down() can restore them
        // without guessing which were legacy vs. a genuine unified-pool
        // product created between the two migrations.
        Schema::create(self::BACKFILL_LOG, function (Blueprint $table): void {
            $table->unsignedBigInteger('id')->primary();
        });

        DB::table(self::BACKFILL_LOG)
            ->insert($ids->map(fn (mixed $id): array => ['id' => $id])->all());
    }

    public function down(): void
    {
        $ids = DB::table(self::BACKFILL_LOG)->pluck('id');

        DB::table('products')
            ->whereIn('id', $ids)
            ->update(['is_batch_tracked' => false]);

        Schema::dropIfExists(self::BACKFILL_LOG);
    }
};
