<?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('guides', function (Blueprint $table) {
            $table->id();
            $table->string('name')->comment('指引名称');
            $table->text('description')->nullable()->comment('指引描述');
            $table->string('category', 50)->default('operation')->comment('分类: operation/fault_handling/training');
            $table->json('tags')->nullable()->comment('标签');
            $table->string('status', 20)->default('draft')->comment('状态: draft/published/archived');
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index('category');
            $table->index('status');
        });

        Schema::create('guide_pages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('guide_id')->constrained()->cascadeOnDelete();
            $table->string('title')->comment('页面标题');
            $table->string('html_url', 500)->comment('HTML页面链接');
            $table->json('options')->nullable()->comment('分支选项(定义输出端口)');
            $table->timestamps();

            $table->index('guide_id');
        });

        Schema::create('guide_page_edges', function (Blueprint $table) {
            $table->id();
            $table->foreignId('guide_id')->constrained()->cascadeOnDelete();
            $table->foreignId('from_page_id')->constrained('guide_pages')->cascadeOnDelete();
            $table->foreignId('to_page_id')->constrained('guide_pages')->cascadeOnDelete();
            $table->string('label', 100)->nullable()->comment('选项按钮文字, null=顺序连接');
            $table->unsignedInteger('sort')->default(0)->comment('选项排序');
            $table->timestamps();

            $table->unique(['from_page_id', 'label']);
            $table->index('guide_id');
            $table->index('to_page_id');
        });

        Schema::create('guide_station', function (Blueprint $table) {
            $table->id();
            $table->foreignId('station_id')->constrained()->cascadeOnDelete();
            $table->foreignId('guide_id')->constrained()->cascadeOnDelete();
            $table->timestamps();

            $table->unique(['station_id', 'guide_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('guide_station');
        Schema::dropIfExists('guide_page_edges');
        Schema::dropIfExists('guide_pages');
        Schema::dropIfExists('guides');
    }
};
