<?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 function hasForeignKey(string $table, string $column): bool
    {
        $schema = config('database.connections.mysql.database');
        $result = DB::selectOne(
            'SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL LIMIT 1',
            [$schema, $table, $column],
        );

        return $result !== null;
    }

    public function up(): void
    {
        if (! Schema::hasColumn('cutting_results', 'product_name')) {
            Schema::table('cutting_results', function (Blueprint $table) {
                $table->string('product_name', 255)->nullable()->after('id');
            });

            DB::statement('
                UPDATE cutting_results cr
                JOIN product_variants pv ON cr.product_variant_id = pv.id
                JOIN products p ON pv.product_id = p.id
                SET cr.product_name = p.name
                WHERE cr.product_name IS NULL
                  AND cr.product_variant_id IS NOT NULL
            ');
        }

        if (Schema::hasColumn('cutting_results', 'product_variant_id')) {
            Schema::table('cutting_results', function (Blueprint $table) {
                if ($this->hasForeignKey('cutting_results', 'product_variant_id')) {
                    $table->dropForeign(['product_variant_id']);
                }
                $table->dropColumn('product_variant_id');
            });
        }

        if (Schema::hasColumn('cutting_results', 'variant_name')) {
            Schema::table('cutting_results', function (Blueprint $table) {
                $table->dropColumn('variant_name');
            });
        }
    }

    public function down(): void
    {
        if (! Schema::hasColumn('cutting_results', 'product_variant_id')) {
            Schema::table('cutting_results', function (Blueprint $table) {
                $table->foreignId('product_variant_id')->nullable()->after('cutting_id')->constrained()->restrictOnDelete();
            });
        }

        if (Schema::hasColumn('cutting_results', 'product_name')) {
            Schema::table('cutting_results', function (Blueprint $table) {
                $table->dropColumn('product_name');
            });
        }

        if (! Schema::hasColumn('cutting_results', 'variant_name')) {
            Schema::table('cutting_results', function (Blueprint $table) {
                $table->string('variant_name', 255)->nullable();
            });
        }
    }
};
