<?php

namespace App\Models;

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

class AIInsight extends Model
{
    use HasFactory;

    protected $table = 'ai_insights';

    protected $fillable = [
        'conversation_id',
        'insight_type',
        'content',
        'confidence_score',
        'metadata',
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'metadata' => 'array',
        'confidence_score' => 'float'
    ];

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

    /**
     * Scope for specific insight types
     */
    public function scopeType($query, string $type)
    {
        return $query->where('insight_type', $type);
    }

    /**
     * Scope for high confidence insights
     */
    public function scopeHighConfidence($query, float $threshold = 0.8)
    {
        return $query->where('confidence_score', '>=', $threshold);
    }

    /**
     * Get insight type badge
     */
    public function getTypeBadgeAttribute(): string
    {
        $badges = [
            'intent' => 'badge bg-primary',
            'entity' => 'badge bg-info',
            'sentiment' => 'badge bg-success',
            'action_item' => 'badge bg-warning',
            'next_step' => 'badge bg-secondary',
            'objection' => 'badge bg-danger',
            'interest' => 'badge bg-success',
            'pain_point' => 'badge bg-danger',
            'urgency' => 'badge bg-warning',
            'timeline' => 'badge bg-info',
            'budget' => 'badge bg-success',
            'solution' => 'badge bg-primary'
        ];

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

    /**
     * Get confidence level
     */
    public function getConfidenceLevelAttribute(): string
    {
        if ($this->confidence_score >= 0.8) return 'High';
        if ($this->confidence_score >= 0.6) return 'Medium';
        return 'Low';
    }
}