<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (!Schema::hasTable('items_upsells')) {
            Schema::create('items_upsells', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('item_id');
                $table->integer('upsell_item_id');
                $table->smallInteger('order')->default(0);
                $table->timestamps();

                // A product can't list the same upsell twice.
                $table->unique(['item_id', 'upsell_item_id']);

                // Drop association rows when either referenced product is deleted.
                $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
                $table->foreign('upsell_item_id')->references('id')->on('items')->onDelete('cascade');
            });
        }
    }

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