<?php
namespace App\Http\Controllers;

use App\Models\AiKbDraft;
use App\Models\AiResponseTemplate;
use App\Models\Ticket;
use App\Services\AiResponseService;
use Illuminate\Http\Request;

class AiResponseController extends Controller
{
    public function __construct(private AiResponseService $svc) {}

    private function agentGuard(): void {
        abort_unless(auth()->user()->hasAnyRole(['agente','jefe_soporte','admin','superadmin']), 403);
    }

    // GET /ai/response/{ticket} — Generar borrador de respuesta
    public function generate(Ticket $ticket)
    {
        $this->agentGuard();
        $ticket->load(['requester','category','type','priority','aiClassification.suggestedCategory','aiClassification.suggestedPriority']);
        $result = $this->svc->generateResponse($ticket);

        if (!$result) {
            return response()->json(['success' => false, 'message' => 'No se encontró una plantilla adecuada para este ticket.']);
        }
        return response()->json(['success' => true, 'data' => $result]);
    }

    // POST /ai/response/{template}/accept — Agente aceptó la respuesta
    public function accept(AiResponseTemplate $template)
    {
        $this->agentGuard();
        $template->increment('accepted');
        return response()->json(['success' => true]);
    }

    // GET /ai/kb-drafts — Lista de borradores KB pendientes
    public function kbDrafts()
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $drafts = AiKbDraft::with(['ticket','category','publishedArticle'])
            ->pending()->latest()->paginate(20);
        return view('ai.kb-drafts', compact('drafts'));
    }

    // GET /ai/kb-drafts/{draft} — Editar borrador KB
    public function editDraft(AiKbDraft $draft)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $draft->load(['ticket','category']);
        $categories = \App\Models\KbCategory::active()->orderBy('name')->get();
        return view('ai.kb-draft-edit', compact('draft','categories'));
    }

    // POST /ai/kb-drafts/{draft}/publish — Publicar borrador como artículo
    public function publishDraft(Request $request, AiKbDraft $draft)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $data = $request->validate([
            'title'       => 'required|string|max:255',
            'excerpt'     => 'required|string|max:500',
            'content'     => 'required|string',
            'category_id' => 'nullable|exists:kb_categories,id',
        ]);
        $article = $this->svc->publishDraft($draft, $data);
        return redirect()->route('kb.show', $article->slug)
            ->with('success', 'Artículo publicado en la Base de Conocimiento.');
    }

    // POST /ai/kb-drafts/{draft}/reject — Descartar borrador
    public function rejectDraft(AiKbDraft $draft)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin','jefe_soporte']), 403);
        $draft->update(['status' => 'rejected']);
        return response()->json(['success' => true, 'message' => 'Borrador descartado.']);
    }

    // Admin: gestión de plantillas de respuesta
    public function templates()
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $templates  = AiResponseTemplate::with('category')->orderBy('name')->paginate(20);
        $categories = \App\Models\TicketCategory::orderBy('name')->get();
        return view('ai.templates', compact('templates','categories'));
    }

    public function storeTemplate(Request $request)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate([
            'name'             => 'required|string|max:255',
            'trigger_keywords' => 'required|string',
            'category_id'      => 'nullable|exists:ticket_categories,id',
            'ticket_type'      => 'nullable|string|max:50',
            'template_body'    => 'required|string',
            'min_confidence'   => 'integer|min:0|max:100',
        ]);
        $data['trigger_keywords'] = array_map('trim', explode(',', $data['trigger_keywords']));
        AiResponseTemplate::create($data);
        return back()->with('success', 'Plantilla creada correctamente.');
    }

    public function updateTemplate(Request $request, AiResponseTemplate $template)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $data = $request->validate([
            'name'             => 'required|string|max:255',
            'trigger_keywords' => 'required|string',
            'category_id'      => 'nullable|exists:ticket_categories,id',
            'template_body'    => 'required|string',
            'min_confidence'   => 'integer|min:0|max:100',
            'active'           => 'boolean',
        ]);
        $data['trigger_keywords'] = array_map('trim', explode(',', $data['trigger_keywords']));
        $template->update($data);
        return back()->with('success', 'Plantilla actualizada.');
    }

    public function destroyTemplate(AiResponseTemplate $template)
    {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
        $template->delete();
        return back()->with('success', 'Plantilla eliminada.');
    }
}
