<?php

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

/**
 * Tedarikçi çoklu tip: bir tedarikçi birden fazla hizmet alanında olabilir
 * (ör. hem otel hem restoran). `suppliers.supplier_type` "birincil tip" olarak
 * korunur; ek tipler bu pivotta tutulur.
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::create('supplier_supplier_type', function (Blueprint $table) {
            $table->id();
            $table->foreignId('supplier_id')->constrained()->cascadeOnDelete();
            $table->string('supplier_type', 30); // hotel, transportation, restaurant, insurance, visa, airline
            $table->timestamps();

            $table->unique(['supplier_id', 'supplier_type'], 'sst_supplier_type_unique');
            $table->index('supplier_type');
        });

        // Backfill: her tedarikçinin mevcut birincil tipi pivota kopyalanır.
        DB::table('suppliers')
            ->whereNotNull('supplier_type')
            ->orderBy('id')
            ->chunkById(300, function ($rows) {
                $now = now();
                $insert = [];
                foreach ($rows as $r) {
                    $insert[] = [
                        'supplier_id' => $r->id,
                        'supplier_type' => $r->supplier_type,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                }
                if ($insert) {
                    DB::table('supplier_supplier_type')->insertOrIgnore($insert);
                }
            });
    }

    public function down(): void
    {
        Schema::dropIfExists('supplier_supplier_type');
    }
};
