<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Conversation extends Model
{
    protected $fillable = [
        'slug',
        'client_slug',
        'client_first_name',
        'client_last_name',
        'is_active',
        'deleted_by_user',
        'deleted_by_merchant',
        'api_created_at',
        'api_updated_at',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'deleted_by_user' => 'boolean',
        'deleted_by_merchant' => 'boolean',
        'api_created_at' => 'datetime',
        'api_updated_at' => 'datetime',
    ];

    /**
     * Get the messages for the conversation.
     */
    public function messages(): HasMany
    {
        return $this->hasMany(ConversationMessage::class)->orderBy('api_created_at', 'asc');
    }

    /**
     * Get the client's full name.
     */
    public function getClientFullNameAttribute(): string
    {
        return trim($this->client_first_name.' '.$this->client_last_name);
    }

    /**
     * Get the latest message for the conversation.
     */
    public function latestMessage()
    {
        return $this->hasOne(ConversationMessage::class)->latest('api_created_at');
    }
}
