<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('suppliers', function (Blueprint $table) {
            // Rename supplier_name to name for consistency
            $table->renameColumn('supplier_name', 'name');

            // Add missing columns
            $table->string('mobile', 20)->nullable()->after('phone');
            $table->string('city', 100)->nullable()->after('address');
            $table->string('state', 100)->nullable()->after('city');
            $table->string('country', 100)->nullable()->after('state');
            $table->string('postal_code', 20)->nullable()->after('country');
            $table->string('tax_number', 50)->nullable()->after('postal_code');
            $table->string('website')->nullable()->after('tax_number');
            $table->string('bank_name')->nullable()->after('website');
            $table->string('bank_account', 50)->nullable()->after('bank_name');
            $table->string('payment_terms', 100)->default('Net 30')->after('bank_account');
            $table->decimal('credit_limit', 15, 2)->nullable()->after('payment_terms');
            $table->string('currency', 3)->default('USD')->after('credit_limit');
            $table->text('notes')->nullable()->after('currency');
            $table->decimal('rating', 3, 1)->default(0.0)->after('notes');
            $table->foreignId('created_by')->nullable()->constrained('users')->onDelete('set null')->after('rating');
            $table->softDeletes()->after('updated_at');

            // Update status enum to include 'suspended'
            $table->enum('status', ['active', 'inactive', 'suspended'])->default('active')->change();

            // Add additional indexes
            $table->index(['country', 'city']);
            $table->index('rating');
            $table->index(['status', 'created_at']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('suppliers', function (Blueprint $table) {
            // Reverse the changes
            $table->renameColumn('name', 'supplier_name');
            $table->dropColumn([
                'mobile', 'city', 'state', 'country', 'postal_code', 'tax_number',
                'website', 'bank_name', 'bank_account', 'payment_terms', 'credit_limit',
                'currency', 'notes', 'rating', 'created_by', 'deleted_at'
            ]);
            $table->enum('status', ['active', 'inactive'])->default('active')->change();
            $table->dropIndex(['country', 'city']);
            $table->dropIndex('suppliers_rating_index');
            $table->dropIndex(['status', 'created_at']);
        });
    }
};
