<?php

namespace App\Models;

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

class Conversation extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'contact_id',
        'session_id',
        'type',
        'status',
        'context_data',
        'ai_model',
        'total_messages',
        'duration_seconds',
        'sentiment_score',
        'satisfaction_score',
        'outcome',
        'summary',
        'started_at',
        'ended_at'
    ];

    protected $casts = [
        'context_data' => 'array',
        'started_at' => 'datetime',
        'ended_at' => 'datetime',
        'sentiment_score' => 'float',
        'satisfaction_score' => 'float'
    ];

    /**
     * Get the user who owns this conversation
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the contact associated with this conversation
     */
    public function contact(): BelongsTo
    {
        return $this->belongsTo(Contact::class);
    }

    /**
     * Get all messages in this conversation
     */
    public function messages(): HasMany
    {
        return $this->hasMany(ConversationMessage::class);
    }

    /**
     * Get AI insights for this conversation
     */
    public function insights(): HasMany
    {
        return $this->hasMany(AIInsight::class);
    }

    /**
     * Get call transcripts for this conversation
     */
    public function transcripts(): HasMany
    {
        return $this->hasMany(ConversationMessage::class)->where('role', 'system');
    }

    /**
     * Scope for active conversations
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope for completed conversations
     */
    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

    /**
     * Scope for conversations by type
     */
    public function scopeByType($query, string $type)
    {
        return $query->where('type', $type);
    }

    /**
     * Get conversation duration in minutes
     */
    public function getDurationMinutesAttribute(): float
    {
        return $this->duration_seconds ? round($this->duration_seconds / 60, 2) : 0;
    }

    /**
     * Get conversation status badge
     */
    public function getStatusBadgeAttribute(): string
    {
        $badges = [
            'active' => 'badge bg-success',
            'completed' => 'badge bg-primary',
            'paused' => 'badge bg-warning',
            'cancelled' => 'badge bg-danger'
        ];

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

    /**
     * Get conversation type label
     */
    public function getTypeLabelAttribute(): string
    {
        $labels = [
            'sales' => 'Sales Call',
            'support' => 'Customer Support',
            'follow_up' => 'Follow Up',
            'qualification' => 'Lead Qualification',
            'demo' => 'Product Demo'
        ];

        return $labels[$this->type] ?? ucfirst($this->type);
    }

    /**
     * Add a message to the conversation
     */
    public function addMessage(string $role, string $content, array $metadata = []): ConversationMessage
    {
        return $this->messages()->create([
            'role' => $role,
            'content' => $content,
            'metadata' => $metadata,
            'timestamp' => now()
        ]);
    }

    /**
     * Update conversation context
     */
    public function updateContext(array $context): void
    {
        $currentContext = $this->context_data ?? [];
        $this->update([
            'context_data' => array_merge($currentContext, $context)
        ]);
    }

    /**
     * Mark conversation as completed
     */
    public function complete(string $outcome = null, string $summary = null): void
    {
        $this->update([
            'status' => 'completed',
            'outcome' => $outcome,
            'summary' => $summary,
            'ended_at' => now()
        ]);
    }

    /**
     * Get conversation statistics
     */
    public function getStatistics(): array
    {
        $messages = $this->messages;
        
        return [
            'total_messages' => $messages->count(),
            'user_messages' => $messages->where('role', 'user')->count(),
            'ai_messages' => $messages->where('role', 'assistant')->count(),
            'duration_minutes' => $this->duration_minutes,
            'sentiment_score' => $this->sentiment_score,
            'satisfaction_score' => $this->satisfaction_score,
            'last_activity' => $this->messages->max('timestamp')
        ];
    }
}
