<?php

declare(strict_types=1);

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

/**
 * 系统更新可用提醒（按用户、按版本包去重；仅本地读写，不在页面渲染时同步远端）。
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('dberp_system_update_notices')) {
            Schema::create('dberp_system_update_notices', function (Blueprint $table): void {
                $table->id();
                $table->foreignId('user_id')->comment('后台用户 users.id')->constrained('users')->cascadeOnDelete();
                $table->string('notice_key', 191)->comment('去重键，如 system_update:{package_id}');
                $table->string('package_id', 128)->nullable()->comment('官方包标识');
                $table->string('latest_version', 64)->nullable()->comment('最新展示版本');
                $table->unsignedInteger('latest_update_version')->nullable()->comment('最新内部更新号');
                $table->string('notice_level', 32)->default('normal')->comment('提醒级别');
                $table->string('title', 255)->comment('提醒标题');
                $table->text('summary')->nullable()->comment('提醒摘要');
                $table->string('action_url', 512)->nullable()->comment('跳转 URL（系统更新中心）');
                $table->timestamp('read_at')->nullable()->comment('已读时间（UTC）');
                $table->timestamp('dismissed_at')->nullable()->comment('用户忽略时间（UTC）');
                $table->timestamp('resolved_at')->nullable()->comment('已无可用更新或已处理（UTC）');
                $table->json('raw_payload')->nullable()->comment('脱敏快照摘要');
                $table->timestamps();

                $table->unique(['user_id', 'notice_key'], 'uq_dberp_sys_upd_notices_user_key');
                $table->index('user_id', 'idx_dberp_sys_upd_notices_user_id');
                $table->index('notice_key', 'idx_dberp_sys_upd_notices_notice_key');
                $table->index('package_id', 'idx_dberp_sys_upd_notices_package_id');
                $table->index('latest_update_version', 'idx_dberp_sys_upd_notices_latest_upd_ver');
                $table->index('read_at', 'idx_dberp_sys_upd_notices_read_at');
                $table->index('dismissed_at', 'idx_dberp_sys_upd_notices_dismissed_at');
                $table->index('resolved_at', 'idx_dberp_sys_upd_notices_resolved_at');
                $table->index(
                    ['user_id', 'resolved_at', 'dismissed_at', 'read_at'],
                    'idx_dberp_sys_upd_notices_user_unread_lookup',
                );
            });
        }
    }

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