<?php

namespace App\Modules\Chat;

use Illuminate\Support\Facades\Auth;
use App\Models\ValidationModel;
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['thread_id', 'from_id', 'message', 'to', 'channel'];

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

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

        static::creating(function ($model) {
            if (! $model->from_id) {
                $model->from_id = Auth::user()->id;
            }
        });
    }

    /**
     * Get thread ID for two users.
     */
    public static function getThreadId(int $to): string
    {
        return ($to < getAuthUserId()) ? $to.'-'.getAuthUserId() : getAuthUserId().'-'.$to;
    }

    /**
     * Constructs the thread id, which is the two ids of the users joined by dash '-'. The first ID is the lowest one.
     */
    public function setThreadIdAttribute($value): void
    {
        if ($value) {
            $this->attributes['thread_id'] = self::getThreadId($value);
        }
    }

    /**
     * An alias to setThreadIdAttribute.
     */
    public function setToAttribute($value): void
    {
        $this->setThreadIdAttribute($value);
    }

    /**
     * Assigning the channel as the thread_id.
     */
    public function setChannelAttribute($value): void
    {
        if ($value) {
            $this->attributes['thread_id'] = $value;
        }
    }

    /**
     * Determines if the logged in user is the person who sent the message.
     */
    public function getOwnAttribute(): bool
    {
        return ($this->from_id == Auth::user()->id);
    }

    /**
     * Defines the relationship with the user model.
     */
    public function from_user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'from_id');
    }

    /**
     * Scope to get messages for a specific user.
     */
    public function scopeChatUser($query, int $user)
    {
        return $query->where('thread_id', self::getThreadId($user));
    }
}
