<?php

namespace App\Modules\Chat;

use App\Models\ValidationModel;
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Channel extends ValidationModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'chat_channels';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['tag', 'public', 'related_id', 'related_type', 'closed'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['notifications'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'tag' => ['required'],
    ];

    /**
     * The "booting" method of the model.
     */
    public static function boot(): void
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_by = getAuthUserId();
        });
    }

    /**
     * Retrieve the notifications count for a channel.
     */
    public function getNotificationsAttribute(): int
    {
        $user = $this->current_user->first();

        return $user ? $user->pivot->notifications : 0;
    }

    /**
     * Returns all the users that are members of the channel.
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'chat_channel_users')->withTimestamps()->withPivot('notifications');
    }

    /**
     * Gets only the current user with the pivot table for this channel.
     */
    public function current_user(): BelongsToMany
    {
        return $this->users()->where('user_id', getAuthUserId());
    }
}
