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

    private function hasForeignOn(string $column): 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, $column]));
    }

    /** Get 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;
    }

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

        // child->parent map (all nullable per dump => SET NULL on delete)
        $map = [
            'employee_id' => 'employees',
            'supplier_id' => 'suppliers',
            'created_by'  => 'users',
            'updated_by'  => 'users',
        ];

        // 1) Align child column types to parent PK (prevents errno:150)
        foreach ($map as $col => $parent) {
            if (!Schema::hasTable($parent) || !Schema::hasColumn($this->table, $col)) continue;
            $spec = $this->pkSpec($parent);
            if (!$spec) continue;
            $sql = $this->sqlType($spec, true);  // nullable = true
            DB::statement("ALTER TABLE `{$this->table}` MODIFY `{$col}` {$sql}");
        }

        // 2) Add FKs only if parent exists and FK not already present
        Schema::table($this->table, function (Blueprint $t) use ($map) {
            foreach ($map as $col => $parent) {
                if (!Schema::hasTable($parent)) continue;

                $exists = !empty(DB::select("
                    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
                ", [$this->table, $col]));
                if ($exists) continue;

                $fk = "raw_bag_purchases_{$col}_foreign";
                $t->foreign($col, $fk)
                  ->references('id')->on($parent)
                  ->cascadeOnUpdate()
                  ->nullOnDelete();   // matches your nullable columns
            }
        });
    }

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

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

