<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DistMessage extends Model
{
    use HasFactory;

    protected $table = 'dist_messages';
    protected $fillable = ['title', 'content', 'sender_id', 'target_type', 'target_ids', 'created_at', 'updated_at'];

    protected $casts = [
        'target_ids' => 'json',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];



    // 消息的发送者
    public function sender()
    {
        return $this->belongsTo(DistAdminDistributor::class, 'sender_id');
    }

    // 消息的阅读状态
    public function readStatuses()
    {
        return $this->hasMany(DistReadStatus::class, 'message_id');
    }

    // 检查消息是否针对某用户
    public function isForUser($userId)
    {
        if ($this->target_type === 'all') {
            return true;
        }

        if ($this->target_type === 'users' && is_array($this->target_ids)) {
            return in_array($userId, $this->target_ids);
        }

        return false;
    }


}
