<?php
namespace App\Models;

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

class AiResponseTemplate extends Model
{
    protected $fillable = ['name','trigger_keywords','category_id','ticket_type','template_body','min_confidence','uses','accepted','active'];

    protected function casts(): array {
        return ['trigger_keywords' => 'array', 'active' => 'boolean'];
    }

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

    public function scopeActive($q) { return $q->where('active', true); }

    public function getAcceptRateAttribute(): int {
        return $this->uses > 0 ? round(($this->accepted / $this->uses) * 100) : 0;
    }

    // Renderiza la plantilla con variables del ticket
    public function render(Ticket $ticket, ?AiClassification $classification = null): string
    {
        $vars = [
            '{{solicitante}}'  => $ticket->requester->name,
            '{{ticket}}'       => $ticket->number,
            '{{titulo}}'       => $ticket->title,
            '{{categoria}}'    => $classification?->suggestedCategory?->name ?? $ticket->category?->name ?? 'General',
            '{{prioridad}}'    => $ticket->priority->name,
            '{{agente}}'       => auth()->user()->name ?? 'el equipo de soporte',
            '{{empresa}}'      => config('app.name', 'Service Desk'),
        ];
        return strtr($this->template_body, $vars);
    }
}
