<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('reports')) {
            Schema::table('reports', function (Blueprint $table): void {
                if (! Schema::hasColumn('reports', 'moderator_note')) {
                    $table->text('moderator_note')->nullable()->after('details');
                }

                if (! Schema::hasColumn('reports', 'last_moderated_by_id')) {
                    $table->foreignId('last_moderated_by_id')->nullable()->after('status')->constrained('users')->nullOnDelete();
                }

                if (! Schema::hasColumn('reports', 'last_moderated_at')) {
                    $table->timestamp('last_moderated_at')->nullable()->after('last_moderated_by_id');
                }
            });
        }

        if (Schema::hasTable('report_history')) {
            return;
        }

        Schema::create('report_history', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('report_id')->constrained('reports')->cascadeOnDelete();
            $table->foreignId('actor_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('action_type', 80);
            $table->string('summary', 255)->nullable();
            $table->text('note')->nullable();
            $table->json('before_json')->nullable();
            $table->json('after_json')->nullable();
            $table->timestamp('created_at')->useCurrent();

            $table->index('report_id');
            $table->index('action_type');
            $table->index('actor_user_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('report_history');

        if (! Schema::hasTable('reports')) {
            return;
        }

        Schema::table('reports', function (Blueprint $table): void {
            if (Schema::hasColumn('reports', 'last_moderated_by_id')) {
                $table->dropConstrainedForeignId('last_moderated_by_id');
            }

            if (Schema::hasColumn('reports', 'last_moderated_at')) {
                $table->dropColumn('last_moderated_at');
            }

            if (Schema::hasColumn('reports', 'moderator_note')) {
                $table->dropColumn('moderator_note');
            }
        });
    }
};