<?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('story_comments')) {
            Schema::create('story_comments', function (Blueprint $table): void {
                $table->id();
                $table->foreignId('story_id')->constrained('stories')->cascadeOnDelete();
                $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
                $table->foreignId('parent_id')->nullable()->constrained('story_comments')->nullOnDelete();
                $table->text('content')->nullable();
                $table->longText('raw_content')->nullable();
                $table->longText('rendered_content')->nullable();
                $table->boolean('is_approved')->default(true);
                $table->timestamps();
                $table->softDeletes();

                $table->index(['story_id', 'created_at']);
                $table->index(['story_id', 'parent_id', 'is_approved']);
                $table->index(['user_id', 'created_at']);
            });
        }

        if (! Schema::hasTable('story_bookmarks')) {
            Schema::create('story_bookmarks', function (Blueprint $table): void {
                $table->id();
                $table->foreignId('story_id')->constrained('stories')->cascadeOnDelete();
                $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
                $table->timestamps();

                $table->unique(['story_id', 'user_id']);
                $table->index(['user_id', 'created_at']);
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('story_bookmarks');
        Schema::dropIfExists('story_comments');
    }
};