<?php

declare(strict_types=1);

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

/**
 * 报表系统数据库迁移
 *
 * 依据等保 2.0 安全审计：导出操作记录审计日志。
 * 依据《统计法》第九条：统计数据保密。
 * 依据《个人信息保护法》第二十八条：敏感信息脱敏。
 */
return new class extends Migration
{
    public function up(): void
    {
        // 报表
        Schema::create('kylin_reports', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100)->comment('报表名称');
            $table->string('report_type', 20)->comment('报表类型');
            $table->string('category', 50)->nullable()->comment('业务分类');
            $table->text('filters')->nullable()->comment('筛选条件（加密 JSON）');
            $table->text('data')->nullable()->comment('报表数据（加密 JSON）');
            $table->dateTime('generated_at')->comment('生成时间');
            $table->unsignedBigInteger('generated_by')->nullable()->comment('生成人 ID');
            $table->timestamps();
            $table->softDeletes();

            $table->index(['report_type', 'generated_at']);
        });

        // 导出记录
        Schema::create('kylin_report_exports', function (Blueprint $table) {
            $table->id();
            $table->foreignId('report_id')->constrained('kylin_reports')->cascadeOnDelete()->comment('报表 ID');
            $table->string('format', 20)->comment('导出格式');
            $table->unsignedBigInteger('exported_by')->nullable()->comment('导出人 ID');
            $table->dateTime('exported_at')->comment('导出时间');
            $table->string('ip_address', 45)->nullable()->comment('导出 IP');
            $table->string('status', 20)->default('completed')->comment('状态');
            $table->timestamps();

            $table->index(['report_id', 'exported_at']);
        });
    }

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