package license

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

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

// HTTPHandler 提供管理端 License 查看与上传接口。
type HTTPHandler struct {
	manager  *Manager
	identity *identity.Service
	mux      *http.ServeMux
}

func NewHTTPHandler(manager *Manager, identityService *identity.Service) *HTTPHandler {
	h := &HTTPHandler{manager: manager, identity: identityService, mux: http.NewServeMux()}
	h.mux.HandleFunc("GET /api/v1/admin/license", h.get)
	h.mux.HandleFunc("POST /api/v1/admin/license", h.upload)
	return h
}

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

func (h *HTTPHandler) require(w http.ResponseWriter, r *http.Request, permission string) (identity.Account, bool) {
	account, err := h.identity.Authenticate(r.Context(), identity.KindAdmin, r.Header.Get("Authorization"))
	if err != nil {
		apiresponse.Error(w, http.StatusUnauthorized, "登录状态无效或已过期")
		return identity.Account{}, false
	}
	if !identity.HasPermission(account, permission) {
		apiresponse.Error(w, http.StatusForbidden, "缺少 License 管理权限")
		return identity.Account{}, false
	}
	return account, true
}

func (h *HTTPHandler) get(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionSystemManage); !ok {
		return
	}
	apiresponse.OK(w, h.manager.Summary())
}

func (h *HTTPHandler) upload(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionSystemManage); !ok {
		return
	}
	var input struct {
		Content string `json:"content"`
	}
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	decoder.DisallowUnknownFields()
	if decoder.Decode(&input) != nil || len(input.Content) > 256<<10 {
		apiresponse.Error(w, http.StatusBadRequest, "请求格式无效")
		return
	}
	if err := h.manager.Load([]byte(input.Content)); err != nil {
		apiresponse.Error(w, http.StatusBadRequest, FormatError(err))
		return
	}
	apiresponse.OK(w, h.manager.Summary())
}
