<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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

/**
 * Tool 能力调用审计（只记录调用元数据，不保存完整 input/output）。
 */
return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('dberp_tool_invocations')) {
            return;
        }

        Schema::create('dberp_tool_invocations', function (Blueprint $table): void {
            $table->id();
            $table->string('tool_name', 128)->comment('Tool 名称，如 inventory.get');
            $table->unsignedInteger('tool_version')->nullable()->comment('Tool 版本；未解析到实现时为空');
            $table->foreignId('actor_user_id')
                ->nullable()
                ->comment('执行身份 users.id；无效 actor 时为空')
                ->constrained('users')
                ->nullOnDelete();
            $table->string('source', 32)->comment('ExecutionSource');
            $table->string('client_id', 64)->nullable()->comment('可选客户端标识');
            $table->string('session_id', 64)->nullable()->comment('可选会话标识');
            $table->string('correlation_id', 36)->comment('调用关联 ID');
            $table->string('permission_type', 32)->nullable()->comment('PERMISSION 或 REPORT');
            $table->string('permission_value', 128)->nullable()->comment('权限码或报表键');
            $table->string('risk', 32)->nullable()->comment('ToolRisk');
            $table->boolean('success')->comment('是否执行成功');
            $table->string('error_code', 64)->nullable()->comment('失败时的稳定错误码');
            $table->unsignedInteger('duration_ms')->comment('调用耗时（毫秒）');
            $table->timestamp('created_at')->comment('写入时间（UTC）');

            $table->index('tool_name', 'idx_dberp_tool_invocations_tool_name');
            $table->index('actor_user_id', 'idx_dberp_tool_invocations_actor_user_id');
            $table->index('correlation_id', 'idx_dberp_tool_invocations_correlation_id');
            $table->index('created_at', 'idx_dberp_tool_invocations_created_at');
        });
    }

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