package contentpolicy

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

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

type AdminHTTPHandler struct {
	store    *Store
	engine   *Engine
	identity *identity.Service
	mux      *http.ServeMux
}

func NewAdminHTTPHandler(store *Store, engine *Engine, identityService *identity.Service) *AdminHTTPHandler {
	h := &AdminHTTPHandler{store: store, engine: engine, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("GET /api/v1/admin/content-policies", h.list)
	h.mux.HandleFunc("POST /api/v1/admin/content-policies", h.create)
	h.mux.HandleFunc("PUT /api/v1/admin/content-policies/{policy_id}", h.update)
	h.mux.HandleFunc("DELETE /api/v1/admin/content-policies/{policy_id}", h.delete)
	return h
}
func (h *AdminHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }
func (h *AdminHTTPHandler) list(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionContentPolicyRead); !ok {
		return
	}
	items, err := h.store.List(r.Context())
	if err != nil {
		apiresponse.Error(w, 503, "内容策略服务暂不可用")
		return
	}
	apiresponse.OK(w, items)
}
func (h *AdminHTTPHandler) create(w http.ResponseWriter, r *http.Request) {
	actor, ok := h.require(w, r, identity.PermissionContentPolicyManage)
	if !ok {
		return
	}
	p, ok := decodePolicy(w, r)
	if !ok {
		return
	}
	saved, err := h.store.Save(r.Context(), p, actor.ID, true)
	h.finish(w, r, saved, err)
}
func (h *AdminHTTPHandler) update(w http.ResponseWriter, r *http.Request) {
	actor, ok := h.require(w, r, identity.PermissionContentPolicyManage)
	if !ok {
		return
	}
	p, ok := decodePolicy(w, r)
	if !ok {
		return
	}
	p.ID = r.PathValue("policy_id")
	saved, err := h.store.Save(r.Context(), p, actor.ID, false)
	h.finish(w, r, saved, err)
}
func (h *AdminHTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
	actor, ok := h.require(w, r, identity.PermissionContentPolicyManage)
	if !ok {
		return
	}
	err := h.store.Delete(r.Context(), r.PathValue("policy_id"), actor.ID)
	if errors.Is(err, ErrNotFound) {
		apiresponse.Error(w, 404, "内容策略不存在")
		return
	}
	if err != nil {
		apiresponse.Error(w, 503, "内容策略删除失败")
		return
	}
	_ = h.engine.Reload(r.Context())
	apiresponse.OK(w, map[string]bool{"deleted": true})
}
func (h *AdminHTTPHandler) finish(w http.ResponseWriter, r *http.Request, p Policy, err error) {
	if errors.Is(err, ErrNotFound) {
		apiresponse.Error(w, 404, "内容策略不存在")
		return
	}
	if err != nil {
		apiresponse.Error(w, 400, err.Error())
		return
	}
	_ = h.engine.Reload(r.Context())
	apiresponse.OK(w, p)
}
func decodePolicy(w http.ResponseWriter, r *http.Request) (Policy, bool) {
	var p Policy
	d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	d.DisallowUnknownFields()
	if d.Decode(&p) != nil {
		apiresponse.Error(w, 400, "请求格式无效")
		return p, false
	}
	Normalize(&p)
	if err := ValidateInput(p); err != nil {
		apiresponse.Error(w, 400, err.Error())
		return p, false
	}
	return p, true
}
func (h *AdminHTTPHandler) require(w http.ResponseWriter, r *http.Request, permission string) (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
	}
	if !identity.HasPermission(a, permission) {
		apiresponse.Error(w, 403, "缺少内容策略权限")
		return a, false
	}
	return a, true
}
