package pricing

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

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/model-prices", h.list)
	h.mux.HandleFunc("POST /api/v1/admin/model-prices", h.create)
	h.mux.HandleFunc("PUT /api/v1/admin/model-prices/{price_id}", h.update)
	h.mux.HandleFunc("DELETE /api/v1/admin/model-prices/{price_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.PermissionPricingRead); !ok {
		return
	}
	items, err := h.service.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) {
	a, ok := h.require(w, r, identity.PermissionPricingManage)
	if !ok {
		return
	}
	p, ok := decode(w, r)
	if !ok {
		return
	}
	saved, err := h.service.Save(r.Context(), p, a.ID, true)
	finish(w, saved, err)
}
func (h *AdminHTTPHandler) update(w http.ResponseWriter, r *http.Request) {
	a, ok := h.require(w, r, identity.PermissionPricingManage)
	if !ok {
		return
	}
	p, ok := decode(w, r)
	if !ok {
		return
	}
	p.ID = r.PathValue("price_id")
	saved, err := h.service.Save(r.Context(), p, a.ID, false)
	finish(w, saved, err)
}
func (h *AdminHTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
	a, ok := h.require(w, r, identity.PermissionPricingManage)
	if !ok {
		return
	}
	err := h.service.Delete(r.Context(), r.PathValue("price_id"), a.ID)
	if errors.Is(err, ErrNotFound) {
		apiresponse.Error(w, 404, "模型价格不存在")
		return
	}
	if err != nil {
		apiresponse.Error(w, 503, "模型价格删除失败")
		return
	}
	apiresponse.OK(w, map[string]bool{"deleted": true})
}
func decode(w http.ResponseWriter, r *http.Request) (Price, bool) {
	var p Price
	d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	d.DisallowUnknownFields()
	if d.Decode(&p) != nil {
		apiresponse.Error(w, 400, "请求格式无效")
		return p, false
	}
	if err := Validate(&p); err != nil {
		apiresponse.Error(w, 400, err.Error())
		return p, false
	}
	return p, true
}
func finish(w http.ResponseWriter, p Price, err error) {
	if errors.Is(err, ErrNotFound) {
		apiresponse.Error(w, 404, "模型价格不存在")
		return
	}
	if err != nil {
		apiresponse.Error(w, 400, err.Error())
		return
	}
	apiresponse.OK(w, p)
}
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
}
