<?php

declare(strict_types=1);

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';

    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);
    }
}
