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

    /** check if a column already has any FK */
    private function hasForeignOn(string $col): bool
    {
        $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";
        return !empty(DB::select($sql, [$this->table, $col]));
    }

    /** read parent PK (type + unsigned) */
    private function pkSpec(string $table): ?array
    {
        $row = DB::selectOne("
            SELECT DATA_TYPE, COLUMN_TYPE
            FROM information_schema.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = ?
              AND COLUMN_NAME = 'id'
            LIMIT 1
        ", [$table]);
        if (!$row) return null;
        $type = strtolower($row->DATA_TYPE); // int | bigint | ...
        $unsigned = str_contains(strtolower($row->COLUMN_TYPE), 'unsigned');
        return ['type' => $type, 'unsigned' => $unsigned];
    }

    private function sqlType(array $spec, bool $nullable): string
    {
        $t = match ($spec['type']) {
            'int'    => 'INT',
            'bigint' => 'BIGINT',
            default  => strtoupper($spec['type']),
        };
        if ($spec['unsigned']) $t .= ' UNSIGNED';
        $t .= $nullable ? ' NULL' : ' NOT NULL';
        return $t;
    }

    /** pick first existing table from candidates */
    private function pick(array $candidates): ?string
    {
        foreach ($candidates as $t) if (Schema::hasTable($t)) return $t;
        return null;
    }

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

        // Map child column -> parent table candidates (edit if your names differ)
        $map = [
            'customer_id' => ['customers', 'clients', 'customer'],
            'supplier_id' => ['suppliers', 'vendors', 'supplier'],
            'warehouse_id'=> ['warehouses', 'stores', 'warehouse'],
            'created_by'  => ['users'],
            'updated_by'  => ['users'],
        ];

        // 1) Align child column types to the chosen parent's PK (prevents errno:150)
        foreach ($map as $col => $candidates) {
            $parent = $this->pick($candidates);
            if (!$parent || !Schema::hasColumn($this->table, $col)) continue;
            $spec = $this->pkSpec($parent);
            if (!$spec) continue;
            $sql  = $this->sqlType($spec, true); // all these columns are nullable in your dump
            DB::statement("ALTER TABLE `{$this->table}` MODIFY `{$col}` {$sql}");
        }

        // 2) Add only the missing FKs (use nullOnDelete because columns are nullable)
        Schema::table($this->table, function (Blueprint $t) use ($map) {
            foreach ($map as $col => $candidates) {
                $parent = null;
                foreach ($candidates as $cand) {
                    if (Schema::hasTable($cand)) { $parent = $cand; break; }
                }
                if (!$parent) continue;           // parent not present yet -> skip
                if ($this->hasForeignOn($col)) continue;

                $fkName = "rmbag_returns_{$col}_foreign";
                $t->foreign($col, $fkName)
                  ->references('id')->on($parent)
                  ->cascadeOnUpdate()
                  ->nullOnDelete();
            }
        });
    }

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

        Schema::table($this->table, function (Blueprint $t) {
            foreach ([
                'rmbag_returns_customer_id_foreign',
                'rmbag_returns_supplier_id_foreign',
                'rmbag_returns_warehouse_id_foreign',
                'rmbag_returns_created_by_foreign',
                'rmbag_returns_updated_by_foreign',
            ] as $fk) {
                try { $t->dropForeign($fk); } catch (\Throwable $e) {}
            }
        });
    }
};

