<?php

namespace App\Models;

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

class ConversationMessage extends Model
{
    use HasFactory;

    protected $table = 'conversation_messages';

    protected $fillable = [
        'conversation_id',
        'role',
        'content',
        'metadata',
        'sentiment',
        'confidence_score',
        'processing_time_ms',
        'timestamp'
    ];

    protected $casts = [
        'metadata' => 'array',
        'timestamp' => 'datetime',
        'confidence_score' => 'float',
        'processing_time_ms' => 'integer'
    ];

    /**
     * Get the conversation that owns this message
     */
    public function conversation(): BelongsTo
    {
        return $this->belongsTo(Conversation::class);
    }

    /**
     * Scope for user messages
     */
    public function scopeUser($query)
    {
        return $query->where('role', 'user');
    }

    /**
     * Scope for assistant messages
     */
    public function scopeAssistant($query)
    {
        return $query->where('role', 'assistant');
    }

    /**
     * Scope for system messages
     */
    public function scopeSystem($query)
    {
        return $query->where('role', 'system');
    }

    /**
     * Get message sentiment badge
     */
    public function getSentimentBadgeAttribute(): string
    {
        $badges = [
            'positive' => 'badge bg-success',
            'negative' => 'badge bg-danger',
            'neutral' => 'badge bg-secondary'
        ];

        return $badges[$this->sentiment] ?? 'badge bg-secondary';
    }

    /**
     * Get formatted timestamp
     */
    public function getFormattedTimestampAttribute(): string
    {
        return $this->timestamp->format('M j, Y g:i A');
    }
}