<?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('fund_transfers')) return;

        Schema::table('fund_transfers', function (Blueprint $table) {

            // accounts (from/to)
            if (Schema::hasTable('accounts')) {
                $table->foreign('from_account_id', 'ft_from_account_fk')
                      ->references('id')->on('accounts')
                      ->onUpdate('cascade')->onDelete('restrict');

                $table->foreign('to_account_id', 'ft_to_account_fk')
                      ->references('id')->on('accounts')
                      ->onUpdate('cascade')->onDelete('restrict');
            }

            // company
            if (Schema::hasTable('companies')) {
                $table->foreign('company_id', 'ft_company_fk')
                      ->references('id')->on('companies')
                      ->onUpdate('cascade')->onDelete('restrict');
            }

            // users
            if (Schema::hasTable('users')) {
                $table->foreign('created_by', 'ft_created_by_fk')
                      ->references('id')->on('users')
                      ->onUpdate('cascade')->onDelete('restrict');

                $table->foreign('updated_by', 'ft_updated_by_fk')
                      ->references('id')->on('users')
                      ->onUpdate('cascade')->onDelete('set null');
            }
        });
    }

    public function down(): void
    {
        if (!Schema::hasTable('fund_transfers')) return;

        Schema::table('fund_transfers', function (Blueprint $table) {
            foreach ([
                'ft_from_account_fk', 'ft_to_account_fk',
                'ft_company_fk', 'ft_created_by_fk', 'ft_updated_by_fk'
            ] as $fk) {
                try { $table->dropForeign($fk); } catch (\Throwable $e) {}
            }
        });
    }
};
