package assistant

import (
	"encoding/json"
	"net/http"

	"aigateway.local/core/internal/identity"
	"aigateway.local/core/internal/platform/apiresponse"
)

// HTTPHandler 管理端 AI 助手接口。
type HTTPHandler struct {
	service  *Service
	identity *identity.Service
	mux      *http.ServeMux
}

func NewHTTPHandler(service *Service, identityService *identity.Service) *HTTPHandler {
	h := &HTTPHandler{service: service, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("POST /api/v1/admin/assistant/chat", h.chat)
	return h
}

func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }

func (h *HTTPHandler) chat(w http.ResponseWriter, r *http.Request) {
	account, err := h.identity.Authenticate(r.Context(), identity.KindAdmin, r.Header.Get("Authorization"))
	if err != nil {
		apiresponse.Error(w, http.StatusUnauthorized, "登录状态无效或已过期")
		return
	}
	if !identity.HasPermission(account, identity.PermissionSystemManage) {
		apiresponse.Error(w, http.StatusForbidden, "缺少系统管理权限")
		return
	}
	var input struct {
		Message string `json:"message"`
	}
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	decoder.DisallowUnknownFields()
	if decoder.Decode(&input) != nil || input.Message == "" || len(input.Message) > 8000 {
		apiresponse.Error(w, http.StatusBadRequest, "消息不能为空且不超过 8000 字符")
		return
	}
	answer, err := h.service.Answer(r.Context(), input.Message)
	if err != nil {
		apiresponse.Error(w, http.StatusServiceUnavailable, err.Error())
		return
	}
	apiresponse.OK(w, map[string]any{"answer": answer})
}
