<?php

namespace App\Models;

/**
 * One row per ClaudeService call, success or failure — see
 * CreateAiCallLogTable's migration comment. Written exclusively by
 * ClaudeService::logCall(); every other AI feature controller only ever
 * reads this table (via AiCallLogController's audit list), never writes
 * to it directly, so there is exactly one place a row can be created.
 */
class AiCallLogModel extends TenantModel
{
    protected $table            = 'ai_call_log';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = '';

    protected $allowedFields = [
        'feature',
        'related_type',
        'related_id',
        'model',
        'system_prompt',
        'request_messages',
        'tool_calls',
        'response_text',
        'input_tokens',
        'output_tokens',
        'success',
        'error_message',
        'triggered_by',
    ];

    /** The Ai Call Log audit page's "Feature" filter dropdown — real distinct values, not a guessed fixed list. */
    public function distinctFeatures(): array
    {
        $rows = $this->distinct()->select('feature')->orderBy('feature', 'asc')->findAll();

        return array_column($rows, 'feature');
    }
}
