<?php

namespace App\Models;

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

class ChatMessage extends Model
{
    use HasFactory;

    /**
     * The database connection that should be used by the model.
     *
     * @var string
     */
    protected $connection = 'mysql';

    protected $fillable = [
        'sender_id',
        'sender_type', // 'admin', 'tenant', 'customer'
        'receiver_id',
        'receiver_type', // 'admin', 'tenant', 'customer'
        'message',
        'is_read',
        'read_at',
        'chat_session_id'
    ];

    protected $casts = [
        'is_read' => 'boolean',
        'read_at' => 'datetime',
    ];

    public function sender()
    {
        if ($this->sender_type === 'admin') {
            return $this->belongsTo(User::class, 'sender_id');
        } elseif ($this->sender_type === 'tenant') {
            return $this->belongsTo(Tenant::class, 'sender_id');
        } else {
            return $this->belongsTo(Customer::class, 'sender_id');
        }
    }

    public function receiver()
    {
        if ($this->receiver_type === 'admin') {
            return $this->belongsTo(User::class, 'receiver_id');
        } elseif ($this->receiver_type === 'tenant') {
            return $this->belongsTo(Tenant::class, 'receiver_id');
        } else {
            return $this->belongsTo(Customer::class, 'receiver_id');
        }
    }

    public function chatSession()
    {
        return $this->belongsTo(ChatSession::class, 'chat_session_id');
    }

    public function scopeUnread($query)
    {
        return $query->where('is_read', false);
    }

    public function scopeForAdmin($query)
    {
        return $query->where('receiver_type', 'admin');
    }

    public function scopeFromTenant($query, $tenantId)
    {
        return $query->where('sender_type', 'tenant')
                    ->where('sender_id', $tenantId);
    }

    public function markAsRead()
    {
        $this->update([
            'is_read' => true,
            'read_at' => now()
        ]);
    }
}
