<?php

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

/**
 * Remove the tracking-mode concept end to end: products.tracking_mode_id and
 * the tracking_modes table. Serial handling is data-driven now — a product
 * sells/damages/transfers by serial because serials are actually on file
 * (Product::serials()/hasAvailableSerials()), never because of a flag.
 *
 * down() recreates the table, the column and its FK, and backfills every
 * product to the 'none' mode — the pre-removal default the mode column held
 * for the vast majority of rows.
 */
return new class extends Migration
{
    public function up(): void
    {
        // Not every database carries the constraint: on installs whose
        // products table was built without it, only the index Laravel names
        // alongside an FK survives, and dropping the constraint
        // unconditionally aborts the migration with SQLSTATE 42000 (1091).
        // Dropping the column clears that leftover index either way.
        foreach (Schema::getForeignKeys('products') as $foreignKey) {
            if (in_array('tracking_mode_id', $foreignKey['columns'], true)) {
                Schema::table('products', function (Blueprint $table) use ($foreignKey) {
                    $table->dropForeign($foreignKey['name'] ?? ['tracking_mode_id']);
                });
            }
        }

        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn('tracking_mode_id');
        });

        Schema::dropIfExists('tracking_modes');
    }

    public function down(): void
    {
        Schema::create('tracking_modes', function (Blueprint $table) {
            $table->id();
            $table->string('code')->unique();
            $table->string('name');
            $table->unsignedTinyInteger('sort_order')->default(0);
        });

        DB::table('tracking_modes')->insert([
            ['code' => 'none', 'name' => 'None', 'sort_order' => 1],
            ['code' => 'serial', 'name' => 'Serial', 'sort_order' => 2],
            ['code' => 'batch', 'name' => 'Batch', 'sort_order' => 3],
            ['code' => 'batch_serial', 'name' => 'Batch + Serial', 'sort_order' => 4],
        ]);

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

        DB::table('products')
            ->whereNull('tracking_mode_id')
            ->update(['tracking_mode_id' => DB::table('tracking_modes')->where('code', 'none')->value('id')]);
    }
};
