package factcheck

import (
	"aigateway.local/core/internal/identity"
	"aigateway.local/core/internal/platform/apiresponse"
	"encoding/json"
	"errors"
	"net/http"
	"strconv"
	"strings"
)

type AdminHTTPHandler struct {
	service  *Service
	identity *identity.Service
	mux      *http.ServeMux
}

func NewAdminHTTPHandler(service *Service, identityService *identity.Service) *AdminHTTPHandler {
	h := &AdminHTTPHandler{service: service, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("GET /api/v1/admin/fact-check/settings", h.getSettings)
	h.mux.HandleFunc("PUT /api/v1/admin/fact-check/settings", h.saveSettings)
	h.mux.HandleFunc("GET /api/v1/admin/fact-check/policies", h.policies)
	h.mux.HandleFunc("POST /api/v1/admin/fact-check/policies", h.savePolicy)
	h.mux.HandleFunc("PUT /api/v1/admin/fact-check/policies/{id}", h.savePolicy)
	h.mux.HandleFunc("DELETE /api/v1/admin/fact-check/policies/{id}", h.deletePolicy)
	h.mux.HandleFunc("GET /api/v1/admin/fact-check/events", h.events)
	h.mux.HandleFunc("GET /api/v1/admin/fact-check/events/{id}", h.event)
	return h
}
func (h *AdminHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }
func (h *AdminHTTPHandler) account(w http.ResponseWriter, r *http.Request, manage bool) (identity.Account, bool) {
	a, err := h.identity.Authenticate(r.Context(), identity.KindAdmin, r.Header.Get("Authorization"))
	if err != nil {
		apiresponse.Error(w, 401, "登录状态无效")
		return a, false
	}
	permission := identity.PermissionKnowledgeRead
	if manage {
		permission = identity.PermissionKnowledgeManage
	}
	if !identity.HasPermission(a, permission) {
		apiresponse.Error(w, 403, "缺少事实核验管理权限")
		return a, false
	}
	return a, true
}
func decodeFact(w http.ResponseWriter, r *http.Request, target any) bool {
	d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	d.DisallowUnknownFields()
	if err := d.Decode(target); err != nil {
		apiresponse.Error(w, 400, "请求格式无效")
		return false
	}
	return true
}
func factError(w http.ResponseWriter, err error) {
	if errors.Is(err, ErrNotFound) {
		apiresponse.Error(w, 404, "资源不存在")
		return
	}
	apiresponse.Error(w, 400, err.Error())
}
func (h *AdminHTTPHandler) getSettings(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.account(w, r, false); !ok {
		return
	}
	x, err := h.service.Settings(r.Context())
	if err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, x)
}
func (h *AdminHTTPHandler) saveSettings(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r, true)
	if !ok {
		return
	}
	var x Settings
	if !decodeFact(w, r, &x) {
		return
	}
	x, err := h.service.SaveSettings(r.Context(), x, a.ID)
	if err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, x)
}
func (h *AdminHTTPHandler) policies(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.account(w, r, false); !ok {
		return
	}
	x, err := h.service.Policies(r.Context())
	if err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, map[string]any{"items": x})
}
func (h *AdminHTTPHandler) savePolicy(w http.ResponseWriter, r *http.Request) {
	a, ok := h.account(w, r, true)
	if !ok {
		return
	}
	var x Policy
	if !decodeFact(w, r, &x) {
		return
	}
	if id := r.PathValue("id"); id != "" {
		x.ID = id
	}
	x, err := h.service.SavePolicy(r.Context(), x, a.ID)
	if err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, x)
}
func (h *AdminHTTPHandler) deletePolicy(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.account(w, r, true); !ok {
		return
	}
	if err := h.service.DeletePolicy(r.Context(), r.PathValue("id")); err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, map[string]bool{"deleted": true})
}
func (h *AdminHTTPHandler) events(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.account(w, r, false); !ok {
		return
	}
	limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
	verdict := strings.TrimSpace(r.URL.Query().Get("verdict"))
	x, err := h.service.Events(r.Context(), verdict, limit)
	if err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, map[string]any{"items": x})
}
func (h *AdminHTTPHandler) event(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.account(w, r, false); !ok {
		return
	}
	x, err := h.service.Event(r.Context(), r.PathValue("id"))
	if err != nil {
		factError(w, err)
		return
	}
	apiresponse.OK(w, x)
}
