<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (! Schema::hasTable('vineyard_rows')) {
            return;
        }

    $driver = Schema::getConnection()->getDriverName();

        if ($driver === 'sqlite') {
            // SQLite requires full table rebuilds for altering nullability; skip and rely on fresh migrations.
            return;
        }

        Schema::table('vineyard_rows', function (Blueprint $table) {
            $table->dropForeign(['variety_variation_id']);
        });

        switch ($driver) {
            case 'mysql':
                DB::statement('ALTER TABLE `vineyard_rows` MODIFY `variety_variation_id` BIGINT UNSIGNED NULL');
                break;
            case 'pgsql':
                DB::statement('ALTER TABLE vineyard_rows ALTER COLUMN variety_variation_id DROP NOT NULL');
                break;
            case 'sqlsrv':
                DB::statement('ALTER TABLE vineyard_rows ALTER COLUMN variety_variation_id BIGINT NULL');
                break;
            default:
                return;
        }

        Schema::table('vineyard_rows', function (Blueprint $table) {
            $table->foreign('variety_variation_id')
                ->references('id')
                ->on('variety_variations')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (! Schema::hasTable('vineyard_rows')) {
            return;
        }

    $driver = Schema::getConnection()->getDriverName();

        if ($driver === 'sqlite') {
            return;
        }

        Schema::table('vineyard_rows', function (Blueprint $table) {
            $table->dropForeign(['variety_variation_id']);
        });

        switch ($driver) {
            case 'mysql':
                DB::statement('ALTER TABLE `vineyard_rows` MODIFY `variety_variation_id` BIGINT UNSIGNED NOT NULL');
                break;
            case 'pgsql':
                DB::statement('ALTER TABLE vineyard_rows ALTER COLUMN variety_variation_id SET NOT NULL');
                break;
            case 'sqlsrv':
                DB::statement('ALTER TABLE vineyard_rows ALTER COLUMN variety_variation_id BIGINT NOT NULL');
                break;
            default:
                return;
        }

        Schema::table('vineyard_rows', function (Blueprint $table) {
            $table->foreign('variety_variation_id')
                ->references('id')
                ->on('variety_variations')
                ->onDelete('cascade');
        });
    }
};
