<?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
    {
        // Drop Foreign Keys and Index
        Schema::table('comments', function (Blueprint $table) {
            $table->dropForeign(['child_id']);
            $table->dropIndex(['commenter_id', 'commenter_type']);
        });

        // Rename and Drop columns
        Schema::table('comments', function (Blueprint $table) {
            $table->renameColumn('commenter_id', 'user_id');
            $table->dropColumn('commenter_type');
            $table->dropColumn('guest_name');
            $table->dropColumn('guest_email');
            $table->renameColumn('child_id', 'parent_id');
            $table->renameColumn('comment', 'body');
            $table->dropColumn('approved');
        });

        // Add Foreign Keys
        Schema::table('comments', function (Blueprint $table) {
            // Ensure the column is unsigned
            $table->bigInteger('user_id')->unsigned()->change();

            // Add the foreign key constraint
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Drop Foreign Keys
        Schema::table('comments', function (Blueprint $table) {
            $table->dropForeign(['parent_id']);
            $table->dropForeign(['user_id']);
        });

        // Rename and Re-Add Columns
        Schema::table('comments', function (Blueprint $table) {
            $table->renameColumn('user_id', 'commenter_id');
            $table->string('commenter_type')->nullable()->after('commenter_id');
            $table->string('guest_name')->nullable()->after('commenter_type');
            $table->string('guest_email')->nullable()->after('guest_name');
            $table->renameColumn('parent_id', 'child_id');
            $table->renameColumn('body', 'comment');
            $table->boolean('approved')->default(true)->after('comment');
        });

        DB::table('comments')->update([
            'commenter_type' => 'App\Models\User',
        ]);

        // Re-Add foreign key constraint and index
        Schema::table('comments', function (Blueprint $table) {
            $table->foreign('child_id')->references('id')->on('comments')->onDelete('cascade');
            $table->index(['commenter_id', 'commenter_type']);
        });
    }
};
