<?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
{
    public function up(): void
    {
        Schema::table('stock_movements', function (Blueprint $table) {
            // Denormalized snapshot of the product's base unit at the time of the
            // movement (see plan decision A7) — avoids a JOIN for CSV exports.
            $table->foreignId('unit_id')->nullable()->after('quantity_after')->constrained('unit_of_measures')->nullOnDelete();
        });

        // Portable backfill (no UPDATE…JOIN — must run on both MySQL and the
        // SQLite in-memory connection used by the test suite).
        DB::table('products')->whereNotNull('base_unit_id')
            ->select('id', 'base_unit_id')
            ->get()
            ->each(function ($product) {
                DB::table('stock_movements')
                    ->where('product_id', $product->id)
                    ->whereNull('unit_id')
                    ->update(['unit_id' => $product->base_unit_id]);
            });
    }

    public function down(): void
    {
        Schema::table('stock_movements', function (Blueprint $table) {
            $table->dropForeign(['unit_id']);
            $table->dropColumn('unit_id');
        });
    }
};
