<?php

namespace Modules\VetAI\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetAI\Entities\VaiQuery;
use Yajra\DataTables\Facades\DataTables;

class VaiQueryController extends Controller
{
    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (!auth()->user()->can('vet_ai.view_history')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        return view('vetAI::queries.index');
    }

    public function list(Request $request)
    {
        $this->gate();

        $query = VaiQuery::with(['user', 'pet'])->forBusiness($this->biz())->latest();

        if ($request->filled('query_type')) $query->where('query_type', $request->query_type);
        if ($request->filled('status'))     $query->where('status', $request->status);

        return DataTables::of($query)
            ->addColumn('when', fn($r) => optional($r->created_at)->format('d M Y H:i'))
            ->addColumn('user_name', fn($r) => e(optional($r->user)->first_name ?? optional($r->user)->username ?? '—'))
            ->addColumn('pet_name', fn($r) => e(optional($r->pet)->petname ?? '—'))
            ->addColumn('type_badge', function ($r) {
                $map = ['differential' => 'info', 'dosage' => 'primary', 'interaction' => 'warning',
                        'education' => 'success', 'general' => 'default'];
                return '<span class="label label-' . ($map[$r->query_type] ?? 'default') . '">'
                     . ucfirst($r->query_type) . '</span>';
            })
            ->addColumn('status_badge', fn($r) => $r->status === 'success'
                ? '<span class="label label-success">OK</span>'
                : '<span class="label label-danger">Error</span>')
            ->addColumn('tokens', fn($r) => (int) $r->tokens_input + (int) $r->tokens_output)
            ->addColumn('action', fn($r) => '<button class="btn btn-xs btn-info btn-view-query" data-id="'
                . $r->id . '"><i class="fa fa-eye"></i></button>')
            ->rawColumns(['type_badge', 'status_badge', 'action'])
            ->make(true);
    }

    public function show($id)
    {
        $this->gate();
        $q = VaiQuery::with(['user', 'pet'])->forBusiness($this->biz())->findOrFail($id);

        return response()->json([
            'id'       => $q->id,
            'when'     => optional($q->created_at)->format('d M Y H:i'),
            'type'     => ucfirst($q->query_type),
            'user'     => optional($q->user)->first_name ?? optional($q->user)->username ?? '—',
            'pet'      => optional($q->pet)->petname ?? '—',
            'model'    => $q->model,
            'status'   => $q->status,
            'prompt'        => $q->prompt,
            'response'      => $q->response,
            'response_html' => $q->status === 'success' ? VaiQuery::renderMarkdown($q->response) : '',
            'error'         => $q->error,
            'tokens'        => (int) $q->tokens_input . ' in / ' . (int) $q->tokens_output . ' out',
        ]);
    }
}
