<?php

namespace App\Models;

use App\Traits\BelongsToWorkspace;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One row per AI reply that consulted the workspace knowledge base.
 *
 * Powers the /knowledge-base/insights dashboard: deflection rate,
 * most-asked questions, knowledge gaps (was_fallback=true), and the
 * thumbs feedback loop.
 *
 * Written from AIManager::generateReply(). Never updated except for
 * the `was_helpful` thumbs feedback endpoint.
 */
class KbQueryLog extends Model
{
    use BelongsToWorkspace;

    protected $table = 'kb_query_logs';

    protected $fillable = [
        'workspace_id',
        'conversation_id',
        'channel',
        'question',
        'answer',
        'cited_chunk_ids',
        'confidence',
        'was_fallback',
        'was_helpful',
        'provider',
        'model',
        'tokens_in',
        'tokens_out',
        'cost_usd',
    ];

    protected function casts(): array
    {
        return [
            'cited_chunk_ids' => 'array',
            'confidence' => 'integer',
            'was_fallback' => 'boolean',
            'was_helpful' => 'boolean',
            'tokens_in' => 'integer',
            'tokens_out' => 'integer',
            'cost_usd' => 'decimal:6',
        ];
    }

    public function workspace(): BelongsTo
    {
        return $this->belongsTo(Workspace::class);
    }

    public function conversation(): BelongsTo
    {
        return $this->belongsTo(Conversation::class);
    }

    /**
     * Resolve the cited KbChunk models on demand. Stored as bare IDs
     * because chunks can be deleted and we still want the log row to
     * survive the dangling references (returns only chunks that still
     * exist).
     */
    public function citedChunks()
    {
        $ids = $this->cited_chunk_ids ?? [];
        if (empty($ids)) {
            return collect();
        }
        return KbChunk::with('document')->whereIn('id', $ids)->get();
    }

    // Scopes powering the Insights dashboard.

    public function scopeAnswered(Builder $query): Builder
    {
        return $query->where('was_fallback', false);
    }

    public function scopeFallback(Builder $query): Builder
    {
        return $query->where('was_fallback', true);
    }

    public function scopeHelpful(Builder $query): Builder
    {
        return $query->where('was_helpful', true);
    }

    public function scopeUnhelpful(Builder $query): Builder
    {
        return $query->where('was_helpful', false);
    }
}
