<?php

declare(strict_types=1);

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

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;

/**
 * 系统更新可用提醒（按用户 + notice_key 去重）。
 *
 * @property int $user_id
 * @property string $notice_key
 * @property string|null $package_id
 * @property string|null $latest_version
 * @property int|null $latest_update_version
 * @property string $notice_level
 * @property string $title
 * @property string|null $summary
 * @property string|null $action_url
 * @property Carbon|null $read_at
 * @property Carbon|null $dismissed_at
 * @property Carbon|null $resolved_at
 * @property array<string, mixed>|null $raw_payload
 */
class DberpSystemUpdateNotice extends Model
{
    public const NOTICE_LEVEL_NORMAL = 'normal';

    public const NOTICE_LEVEL_REQUIRED = 'required';

    protected $table = 'dberp_system_update_notices';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'user_id',
        'notice_key',
        'package_id',
        'latest_version',
        'latest_update_version',
        'notice_level',
        'title',
        'summary',
        'action_url',
        'read_at',
        'dismissed_at',
        'resolved_at',
        'raw_payload',
    ];

    protected function casts(): array
    {
        return [
            'latest_update_version' => 'integer',
            'read_at' => 'datetime',
            'dismissed_at' => 'datetime',
            'resolved_at' => 'datetime',
            'raw_payload' => 'array',
        ];
    }

    /**
     * @param  Builder<self>  $query
     * @return Builder<self>
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->notDismissed()->unresolved();
    }

    /**
     * @param  Builder<self>  $query
     * @return Builder<self>
     */
    public function scopeUnread(Builder $query): Builder
    {
        return $query->whereNull('read_at');
    }

    /**
     * @param  Builder<self>  $query
     * @return Builder<self>
     */
    public function scopeForUser(Builder $query, int $userId): Builder
    {
        return $query->where('user_id', $userId);
    }

    /**
     * @param  Builder<self>  $query
     * @return Builder<self>
     */
    public function scopeNotDismissed(Builder $query): Builder
    {
        return $query->whereNull('dismissed_at');
    }

    /**
     * @param  Builder<self>  $query
     * @return Builder<self>
     */
    public function scopeUnresolved(Builder $query): Builder
    {
        return $query->whereNull('resolved_at');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
