<?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 = 'items';

    // Helper: does a column already have any FK?
    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]));
    }

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

        // Parent tables presence
        $hasCompanies  = Schema::hasTable('companies');
        $hasWarehouses = Schema::hasTable('warehouses');
        $hasCategories = Schema::hasTable('categories');

        // Which FKs are missing?
        $needCompanyFk  = $hasCompanies  && !$this->hasForeignOn($this->table, 'company_id');
        $needWarehouseFk= $hasWarehouses && !$this->hasForeignOn($this->table, 'warehouse_id');
        $needCategoryFk = $hasCategories && !$this->hasForeignOn($this->table, 'category_id');

        if (!($needCompanyFk || $needWarehouseFk || $needCategoryFk)) return;

        Schema::table($this->table, function (Blueprint $table) use ($needCompanyFk, $needWarehouseFk, $needCategoryFk) {
            // Use Laravel default-style names to match your existing constraints
            if ($needCompanyFk) {
                $table->foreign('company_id', 'items_company_id_foreign')
                      ->references('id')->on('companies')
                      ->cascadeOnUpdate()
                      ->restrictOnDelete(); // company_id is NOT NULL in your schema
            }

            if ($needWarehouseFk) {
                $table->foreign('warehouse_id', 'items_warehouse_id_foreign')
                      ->references('id')->on('warehouses')
                      ->cascadeOnUpdate()
                      ->nullOnDelete(); // warehouse_id is nullable
            }

            if ($needCategoryFk) {
                $table->foreign('category_id', 'items_category_id_foreign')
                      ->references('id')->on('categories')
                      ->cascadeOnUpdate()
                      ->nullOnDelete(); // category_id is nullable
            }
        });
    }

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

        Schema::table($this->table, function (Blueprint $table) {
            foreach ([
                'items_company_id_foreign',
                'items_warehouse_id_foreign',
                'items_category_id_foreign',
            ] as $fk) {
                try { $table->dropForeign($fk); } catch (\Throwable $e) {}
            }
        });
    }
};
