<?php

namespace Modules\VetAI\Entities;

use Illuminate\Database\Eloquent\Model;
use Modules\VetClinic\Entities\VcPet;
use Modules\VetClinic\Entities\VcAppointment;

class VaiQuery extends Model
{
    protected $table = 'vai_queries';
    protected $guarded = ['id'];

    public function user()
    {
        return $this->belongsTo(\App\User::class, 'user_id');
    }

    public function pet()
    {
        return $this->belongsTo(VcPet::class, 'pet_id');
    }

    public function appointment()
    {
        return $this->belongsTo(VcAppointment::class, 'appointment_id');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    public function getTotalTokensAttribute()
    {
        return (int) $this->tokens_input + (int) $this->tokens_output;
    }

    /** Render an AI (markdown) response to safe HTML for display. */
    public static function renderMarkdown(?string $text): string
    {
        if (empty($text)) {
            return '';
        }
        try {
            return \Illuminate\Support\Str::markdown($text, [
                'html_input'         => 'escape',
                'allow_unsafe_links' => false,
            ]);
        } catch (\Throwable $e) {
            return nl2br(e($text));
        }
    }
}

