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

    private function hasForeignOn(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, [$this->table, $column]));
    }

    /** Read parent PK spec (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 sqlTypeFromSpec(array $spec, bool $nullable = false): 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;

        // Parent availability
        $parents = [
            'company_id'  => 'companies',
            'created_by'  => 'users',
            'updated_by'  => 'users',
            'purchase_id' => 'purchases',
            'item_id'     => 'items',
        ];

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

            $spec = $this->pkSpec($parentTable);
            if (!$spec) continue;

            $nullable = in_array($col, [], true); // all are NOT NULL per your dump
            $sqlType  = $this->sqlTypeFromSpec($spec, $nullable);
            DB::statement("ALTER TABLE `{$this->table}` MODIFY `{$col}` {$sqlType}");
        }

        // 2) Add only the missing FKs (use restrictOnDelete to match your dump)
        Schema::table($this->table, function (Blueprint $t) use ($parents) {
            foreach ($parents as $col => $parentTable) {
                if (!Schema::hasTable($parentTable)) continue;
                if ($this->hasForeignOn($col)) continue;

                $fkName = "purchase_details_{$col}_foreign";
                $t->foreign($col, $fkName)
                  ->references('id')->on($parentTable)
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();
            }
        });
    }

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

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