<?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
    {
        Schema::create('post_tags', function (Blueprint $table) {
            $table->id()->comment('主鍵');

            // section：對應 posts.section（可避免不同區塊標籤混用）
            $table->string('section', 50)->comment('區塊');

            $table->string('name', 100)->comment('名稱');
            $table->string('slug', 150)->comment('Slug');

            $table->unsignedInteger('sort_order')->default(0)->comment('排序');
            $table->boolean('is_active')->default(true)->comment('啟用');

            $table->timestamp('created_at')->nullable()->comment('建立');
            $table->timestamp('updated_at')->nullable()->comment('更新');
            $table->timestamp('deleted_at')->nullable()->comment('刪除');

            $table->unique(['section', 'slug']);
            $table->index(['section', 'sort_order']);
        });

        Schema::create('post_tag_post', function (Blueprint $table) {
            $table->id()->comment('主鍵');

            $table->foreignId('post_id')
                ->constrained('posts')
                ->cascadeOnDelete()
                ->comment('文章');

            $table->foreignId('post_tag_id')
                ->constrained('post_tags')
                ->cascadeOnDelete()
                ->comment('標籤');

            $table->unsignedInteger('sort_order')->default(0)->comment('排序');

            $table->timestamp('created_at')->nullable()->comment('建立');
            $table->timestamp('updated_at')->nullable()->comment('更新');

            $table->unique(['post_id', 'post_tag_id']);
            $table->index(['post_tag_id', 'sort_order']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('post_tag_post');
        Schema::dropIfExists('post_tags');
    }
};
