<?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::create('donor_portfolio_order', function (Blueprint $table) {
            $table->id();
            $table->foreignId('donor_financial_portfolio_id')
                ->constrained('donor_financial_portfolios')
                ->onDelete('cascade')
                ->name('dpo_portfolio_id_foreign');
            $table->foreignId('order_id')
                ->constrained('orders')
                ->onDelete('cascade')
                ->name('dpo_order_id_foreign');
            $table->decimal('allocated_amount', 15, 2)
                ->comment('Amount allocated from this portfolio to this order');
            $table->timestamps();

            // Ensure unique combination to prevent duplicate allocations
            $table->unique(['donor_financial_portfolio_id', 'order_id'], 'dpo_unique');

            // Add indexes for better query performance
            $table->index(['donor_financial_portfolio_id'], 'dpo_portfolio_idx');
            $table->index(['order_id'], 'dpo_order_idx');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('donor_portfolio_order');
    }
};
