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

    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]));
    }

    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;
    }

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

        $parents = [
            'delivery_id' => Schema::hasTable('rm_deliveries') ? 'rm_deliveries' : null,
            'product_id'  => Schema::hasTable('products')      ? 'products'      : null,
        ];

        // 1) Align child types to parent PKs (prevents errno:150)
        foreach ($parents as $col => $parent) {
            if (!$parent || !Schema::hasColumn($this->table, $col)) continue;
            $spec = $this->pkSpec($parent);
            if (!$spec) continue;

            $nullable = false; // both are NOT NULL per dump
            $sqlType  = $this->sqlType($spec, $nullable);
            DB::statement("ALTER TABLE `{$this->table}` MODIFY `{$col}` {$sqlType}");
        }

        // 2) Add FKs if missing
        Schema::table($this->table, function (Blueprint $t) use ($parents) {
            if ($parents['delivery_id'] && !$this->hasForeignOn('delivery_id')) {
                $t->foreign('delivery_id', 'rm_delivery_details_delivery_id_foreign')
                  ->references('id')->on($parents['delivery_id'])
                  ->cascadeOnUpdate()->restrictOnDelete();
            }
            if ($parents['product_id'] && !$this->hasForeignOn('product_id')) {
                $t->foreign('product_id', 'rm_delivery_details_product_id_foreign')
                  ->references('id')->on($parents['product_id'])
                  ->cascadeOnUpdate()->restrictOnDelete();
            }
        });
    }

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

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