<?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
{
    public function up(): void
    {
        // Step 1: Add vendor_type_id column (nullable first so existing rows don't break)
        Schema::table('vendors', function (Blueprint $table) {
            $table->foreignId('vendor_type_id')
                  ->nullable()
                  ->after('category_id')
                  ->constrained('vendor_types')
                  ->nullOnDelete();
        });

        // Step 2: Map old vendor_type string values → new vendor_type_id
        $map = [
            'service_provider'   => 1,
            'food_vendor'        => 2,
            'ride_provider'      => 3,
            'delivery_personnel' => 4,
        ];
        foreach ($map as $slug => $id) {
            DB::table('vendors')->where('vendor_type', $slug)->update(['vendor_type_id' => $id]);
        }

        // Step 3: Drop old vendor_type string column
        Schema::table('vendors', function (Blueprint $table) {
            $table->dropColumn('vendor_type');
        });
    }

    public function down(): void
    {
        Schema::table('vendors', function (Blueprint $table) {
            $table->string('vendor_type')->nullable()->after('category_id');
            $table->dropForeign(['vendor_type_id']);
            $table->dropColumn('vendor_type_id');
        });
    }
};
