<?php

namespace App\Models;

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

class ChatSession extends Model
{
    use HasFactory;

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

    protected $fillable = [
        'tenant_id',
        'customer_id',
        'admin_id',
        'status', // 'active', 'closed', 'archived'
        'last_message_at',
        'started_at'
    ];

    protected $casts = [
        'last_message_at' => 'datetime',
        'started_at' => 'datetime',
    ];

    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function admin()
    {
        return $this->belongsTo(User::class, 'admin_id');
    }

    public function messages()
    {
        return $this->hasMany(ChatMessage::class, 'chat_session_id');
    }

    public function latestMessage()
    {
        return $this->hasOne(ChatMessage::class, 'chat_session_id')
                    ->latest();
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeForTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }

    public function getParticipantNameAttribute()
    {
        if ($this->customer_id) {
            return $this->customer->name;
        }
        return $this->tenant->name;
    }

    public function getParticipantTypeAttribute()
    {
        return $this->customer_id ? 'customer' : 'tenant';
    }
}
