<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class ConversationMessage extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'conversation_id',
        'user_id',
        'message',
        'message_type',
        'media',
        'media_type',
        'viewed_id',
        'deleted_for',
        'file_name'
    ];

    protected $appends = [
        'media_url'
    ];

    protected static function booted()
    {
        static::creating(function(ConversationMessage $conversation_message) {
            $conversation_message->user_id = auth()->user()->id;
        });
    }

    public function getMediaUrlAttribute()
    {
        return is_null($this->media) ? env('uploads_url') . $this->media : null;
    }

    public function conversation()
    {
        return $this->belongsTo(Conversation::class);
    }

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

    public function setMediaAttribute($media)
    {
        if(is_file($media)){
            $this->attributes['media'] = $media ?
                Storage::disk(env('UPLOADS_DISK'))->put('conversation', $media) : null;
        }
    }
}
