<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('item_suppliers', function (Blueprint $table) {
            // Add missing columns
            if (!Schema::hasColumn('item_suppliers', 'is_primary')) {
                $table->boolean('is_primary')->default(false)->after('contact_id');
            }

            if (!Schema::hasColumn('item_suppliers', 'last_price')) {
                $table->decimal('last_price', 18, 4)->nullable()->after('min_order_qty');
            }

            // Add indexes for performance (guard duplicates via information_schema)
            $dbName = DB::getDatabaseName();
            $itemIdxExists = DB::table('information_schema.statistics')
                ->where('table_schema', $dbName)
                ->where('table_name', 'item_suppliers')
                ->where('index_name', 'item_suppliers_item_id_is_primary_index')
                ->exists();
            if (!$itemIdxExists) {
                $table->index(['item_id', 'is_primary']);
            }

            $contactIdxExists = DB::table('information_schema.statistics')
                ->where('table_schema', $dbName)
                ->where('table_name', 'item_suppliers')
                ->where('index_name', 'item_suppliers_contact_id_is_primary_index')
                ->exists();
            if (!$contactIdxExists) {
                $table->index(['contact_id', 'is_primary']);
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('item_suppliers', function (Blueprint $table) {
            $table->dropIndex(['item_id', 'is_primary']);
            $table->dropIndex(['contact_id', 'is_primary']);

            if (Schema::hasColumn('item_suppliers', 'last_price')) {
                $table->dropColumn('last_price');
            }

            if (Schema::hasColumn('item_suppliers', 'is_primary')) {
                $table->dropColumn('is_primary');
            }
        });
    }
};
