<?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('products', function (Blueprint $table) {
            $table->foreignId('base_unit_id')->nullable()->after('sub_category_id')->constrained('unit_of_measures')->nullOnDelete();
            $table->boolean('has_variants')->default(false)->after('base_unit_id');
            $table->unsignedTinyInteger('tracking_mode_id')->nullable()->after('has_variants');
        });

        // Every product existing before unit-awareness defaults to EACH / no tracking.
        $eachId = DB::table('unit_of_measures')->where('code', 'EACH')->value('id');
        $noneId = DB::table('tracking_modes')->where('code', 'none')->value('id');

        if ($eachId) {
            DB::table('products')->whereNull('base_unit_id')->update(['base_unit_id' => $eachId]);
        }
        if ($noneId) {
            DB::table('products')->whereNull('tracking_mode_id')->update(['tracking_mode_id' => $noneId]);
        }

        Schema::table('products', function (Blueprint $table) {
            $table->foreign('tracking_mode_id')->references('id')->on('tracking_modes')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropForeign(['base_unit_id']);
            $table->dropForeign(['tracking_mode_id']);
            $table->dropColumn(['base_unit_id', 'has_variants', 'tracking_mode_id']);
        });
    }
};
