<?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 调用审计补充治理字段。不保存完整入参/出参、提示词或密钥。
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('dberp_tool_invocations')) {
            return;
        }

        if (! Schema::hasColumn('dberp_tool_invocations', 'tool_owner')) {
            Schema::table('dberp_tool_invocations', function (Blueprint $table): void {
                $table->string('tool_owner', 64)->nullable()->comment('core / test / plugin:{alias}');
            });
        }

        if (! Schema::hasColumn('dberp_tool_invocations', 'request_id')) {
            Schema::table('dberp_tool_invocations', function (Blueprint $table): void {
                $table->string('request_id', 128)->nullable()->comment('协议/请求标识，非完整载荷');
            });
        }

        if (! Schema::hasColumn('dberp_tool_invocations', 'page')) {
            Schema::table('dberp_tool_invocations', function (Blueprint $table): void {
                $table->unsignedInteger('page')->nullable()->comment('分页页码（若适用）');
            });
        }

        if (! Schema::hasColumn('dberp_tool_invocations', 'per_page')) {
            Schema::table('dberp_tool_invocations', function (Blueprint $table): void {
                $table->unsignedInteger('per_page')->nullable()->comment('每页条数（若适用）');
            });
        }

        if (! Schema::hasColumn('dberp_tool_invocations', 'result_count')) {
            Schema::table('dberp_tool_invocations', function (Blueprint $table): void {
                $table->unsignedInteger('result_count')->nullable()->comment('本页结果条数，不含完整业务载荷');
            });
        }

        if (! Schema::hasColumn('dberp_tool_invocations', 'filter_fingerprint')) {
            Schema::table('dberp_tool_invocations', function (Blueprint $table): void {
                $table->string('filter_fingerprint', 64)->nullable()->comment('安全过滤指纹（哈希），不含敏感原文');
            });
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('dberp_tool_invocations')) {
            return;
        }

        foreach (['filter_fingerprint', 'result_count', 'per_page', 'page', 'request_id', 'tool_owner'] as $column) {
            if (! Schema::hasColumn('dberp_tool_invocations', $column)) {
                continue;
            }

            Schema::table('dberp_tool_invocations', function (Blueprint $table) use ($column): void {
                $table->dropColumn($column);
            });
        }
    }
};
