<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Adds Client (Buyer) and Seller (Supplier) mapping FK columns to consignments table.
     */
    public function up(): void
    {
        Schema::table('consignments', function (Blueprint $table) {
            // Buyer can be either a Client or Custom Account
            $table->unsignedBigInteger('buyer_client_id')->nullable()->after('investor_share_value');
            $table->unsignedBigInteger('buyer_custom_account_id')->nullable()->after('buyer_client_id');

            // Seller can be either a Client or Custom Account
            $table->unsignedBigInteger('seller_client_id')->nullable()->after('buyer_custom_account_id');
            $table->unsignedBigInteger('seller_custom_account_id')->nullable()->after('seller_client_id');

            // Foreign key constraints
            $table->foreign('buyer_client_id')->references('id')->on('clients')->onDelete('set null');
            $table->foreign('buyer_custom_account_id')->references('id')->on('custom_accounts')->onDelete('set null');
            $table->foreign('seller_client_id')->references('id')->on('clients')->onDelete('set null');
            $table->foreign('seller_custom_account_id')->references('id')->on('custom_accounts')->onDelete('set null');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('consignments', function (Blueprint $table) {
            $table->dropForeign(['buyer_client_id']);
            $table->dropForeign(['buyer_custom_account_id']);
            $table->dropForeign(['seller_client_id']);
            $table->dropForeign(['seller_custom_account_id']);

            $table->dropColumn([
                'buyer_client_id',
                'buyer_custom_account_id',
                'seller_client_id',
                'seller_custom_account_id',
            ]);
        });
    }
};
