<?php

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

return new class extends Migration {
    private string $table = 'issue_raw_material_details';
    // Try these for material parent; put your real table first if you know it
    private array $materialParents = ['materials', 'raw_materials', 'products', 'rm_materials', 'rm_products'];

    private function hasForeignOn(string $table, string $column): bool
    {
        $sql = <<<SQL
SELECT 1
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME   = ?
  AND COLUMN_NAME  = ?
  AND REFERENCED_TABLE_NAME IS NOT NULL
LIMIT 1
SQL;
        return !empty(DB::select($sql, [$table, $column]));
    }

    private function pickExisting(array $names): ?string
    {
        foreach ($names as $n) if (Schema::hasTable($n)) return $n;
        return null;
    }

    public function up(): void
    {
        if (!Schema::hasTable($this->table)) return;

        // Precompute what exists (NO EXCEPTIONS)
        $hasIRMs      = Schema::hasTable('issue_raw_materials');
        $hasBagTypes  = Schema::hasTable('bag_types');
        $hasWarehouses= Schema::hasTable('warehouses');
        $matParent    = $this->pickExisting($this->materialParents);

        $needIssueFk   = !$this->hasForeignOn($this->table, 'issue_raw_material_id') && $hasIRMs;
        $needBagFk     = !$this->hasForeignOn($this->table, 'bag_type_id') && $hasBagTypes;
        $needMatFk     = !$this->hasForeignOn($this->table, 'material_id') && $matParent;
        $needWhFk      = !$this->hasForeignOn($this->table, 'warehouse_id') && $hasWarehouses;

        if ($needIssueFk || $needBagFk || $needMatFk || $needWhFk) {
            Schema::table($this->table, function (Blueprint $t) use ($matParent, $needIssueFk, $needBagFk, $needMatFk, $needWhFk) {
                if ($needIssueFk) {
                    $t->foreign('issue_raw_material_id', 'issue_raw_material_details_issue_raw_material_id_foreign')
                      ->references('id')->on('issue_raw_materials')
                      ->cascadeOnUpdate()
                      ->restrictOnDelete();
                }

                if ($needBagFk) {
                    $t->foreign('bag_type_id', 'issue_raw_material_details_bag_type_id_foreign')
                      ->references('id')->on('bag_types')
                      ->cascadeOnUpdate()
                      ->nullOnDelete();
                }

                if ($needMatFk && $matParent) {
                    $t->foreign('material_id', 'issue_raw_material_details_material_id_foreign')
                      ->references('id')->on($matParent)
                      ->cascadeOnUpdate()
                      ->restrictOnDelete();
                }

                if ($needWhFk) {
                    $t->foreign('warehouse_id', 'issue_raw_material_details_warehouse_id_foreign')
                      ->references('id')->on('warehouses')
                      ->cascadeOnUpdate()
                      ->nullOnDelete();
                }
            });
        }
        // If some parents don't exist yet, this migration still succeeds; you can add the remaining FKs later.
    }

    public function down(): void
    {
        if (!Schema::hasTable($this->table)) return;

        Schema::table($this->table, function (Blueprint $t) {
            foreach ([
                'issue_raw_material_details_issue_raw_material_id_foreign',
                'issue_raw_material_details_bag_type_id_foreign',
                'issue_raw_material_details_material_id_foreign',
                'issue_raw_material_details_warehouse_id_foreign',
            ] as $fk) {
                try { $t->dropForeign($fk); } catch (\Throwable $e) {}
            }
        });
    }
};
