<?php

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

/**
 * Consolidated CMS / content tables (squashed 2026-07-11).
 *
 * Each table is created once with its final schema, guarded with
 * hasTable/hasColumn/hasIndex checks so installs that predate the squash are
 * topped up to the same final schema instead of colliding on CREATE TABLE.
 *
 * Note: the settings table here is structural only (key/value columns). The
 * default settings rows are seeded by the retained timestamped data migrations.
 *
 * Do not add future schema changes to this file — fresh installs and
 * existing installs would diverge. Create a new migration instead.
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $this->createIfMissing('settings', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->text('value')->nullable();
            $table->string('type')->default('string');
            $table->string('group')->default('general');
            $table->text('description')->nullable();
            $table->timestamps();
        });

        $this->createIfMissing('tags', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();

            $table->unique('name');
            $table->unique('slug');
        });

        if (Schema::hasTable('menus')) {
            $this->upgradeExistingMenusTable();
        } else {
            Schema::create('menus', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('slug');
                $table->string('icon')->nullable();
                $table->foreignId('parent_id')->nullable()->constrained('menus')->cascadeOnDelete();
                $table->integer('display_order')->default(0);
                $table->boolean('is_visible')->default(true);
                $table->boolean('requires_auth')->default(false);
                $table->timestamps();

                $table->unique('slug');
            });
        }

        $this->createIfMissing('pages', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->longText('content')->nullable();
            $table->enum('status', ['draft', 'published'])->default('draft');
            $table->boolean('is_special')->default(false);
            $table->foreignId('menu_id')->nullable()->constrained('menus')->nullOnDelete();
            $table->foreignId('submenu_id')->nullable()->constrained('menus')->nullOnDelete();
            $table->boolean('requires_auth')->default(false);
            $table->string('meta_title')->nullable();
            $table->text('meta_description')->nullable();
            $table->integer('display_order')->default(0);
            $table->timestamps();

            $table->unique('slug');
        });

        $this->createIfMissing('blog_posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->string('slug');
            $table->text('excerpt')->nullable();
            $table->text('content');
            $table->string('featured_image')->nullable();
            $table->enum('status', ['draft', 'published', 'archived'])->default('draft');
            $table->timestamp('published_at')->nullable();
            $table->timestamps();

            $table->unique('slug');
            $table->index(['status', 'published_at']);
        });

        $this->createIfMissing('blog_post_tag', function (Blueprint $table) {
            $table->foreignId('blog_post_id')->constrained()->cascadeOnDelete();
            $table->foreignId('tag_id')->constrained('tags')->cascadeOnDelete();
            $table->primary(['blog_post_id', 'tag_id']);
        });
    }

    /**
     * Rollback is intentionally blocked.
     *
     * Squashed migrations consolidate the entire schema into one pass and have
     * no meaningful prior state to restore. Rolling back would drop live data
     * on existing installs, so rollback is intentionally blocked. Use
     * `php artisan migrate:fresh` to rebuild the schema from scratch on a
     * non-production database.
     */
    public function down(): void
    {
        throw new RuntimeException(
            'Squashed migrations cannot be rolled back. Run `php artisan migrate:fresh` to rebuild the schema on a non-production database.'
        );
    }

    /**
     * Bring a pre-squash menus table up to the final schema.
     */
    private function upgradeExistingMenusTable(): void
    {
        Schema::table('menus', function (Blueprint $table) {
            if (! Schema::hasColumn('menus', 'icon')) {
                $table->string('icon')->nullable();
            }
        });
    }

    private function createIfMissing(string $tableName, Closure $callback): void
    {
        if (! Schema::hasTable($tableName)) {
            Schema::create($tableName, $callback);
        }
    }
};
