<?php

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

/**
 * The lot, not the product, is now the price source of truth — the POS only
 * sells lots whose sale_price is on file, and an unpriced lot is invisible to
 * it until a later receipt prices it. Lots received before pricing was moved
 * onto the lot (b3b1f07) never got a sale_price, so those products silently
 * disappeared from the POS. Backfill them with the agreed 500.00 placeholder:
 * it makes every existing consignment sellable again, and the lots that truly
 * should not sell at that price are corrected the same way any price is — on
 * the next receipt or through the stock-batch resource.
 */
return new class extends Migration
{
    private const BACKFILL_PRICE = 500.00;

    private const BACKFILL_LOG = 'stock_batches_sale_price_backfill';

    public function up(): void
    {
        // Re-running up() (fresh deploy re-try, or the migration 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('stock_batches')
            ->whereNull('sale_price')
            ->pluck('id');

        DB::table('stock_batches')
            ->whereNull('sale_price')
            ->update(['sale_price' => self::BACKFILL_PRICE]);

        // Log exactly which rows were touched so down() can restore them
        // without guessing what was priced before.
        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('stock_batches')
            ->whereIn('id', $ids)
            ->update(['sale_price' => null]);

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