package modelquota

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

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

// HTTPHandler 提供管理端模型配额 CRUD。
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("GET /api/v1/admin/model-quotas", h.list)
	h.mux.HandleFunc("POST /api/v1/admin/model-quotas", h.save)
	h.mux.HandleFunc("PUT /api/v1/admin/model-quotas/{quota_id}", h.save)
	h.mux.HandleFunc("DELETE /api/v1/admin/model-quotas/{quota_id}", h.delete)
	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, "缺少模型配额管理权限")
		return identity.Account{}, false
	}
	return account, true
}

func (h *HTTPHandler) 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, http.StatusServiceUnavailable, "模型配额查询失败")
		return
	}
	apiresponse.OK(w, items)
}

type quotaInput struct {
	ProviderCode      string `json:"provider_code"`
	ModelPattern      string `json:"model_pattern"`
	MonthlyTokenQuota int64  `json:"monthly_token_quota"`
	Enabled           *bool  `json:"enabled"`
}

func (h *HTTPHandler) save(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionPricingManage); !ok {
		return
	}
	var input quotaInput
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	decoder.DisallowUnknownFields()
	if decoder.Decode(&input) != nil {
		apiresponse.Error(w, http.StatusBadRequest, "请求格式无效")
		return
	}
	enabled := true
	if input.Enabled != nil {
		enabled = *input.Enabled
	}
	item, err := h.service.Save(r.Context(), r.PathValue("quota_id"), input.ProviderCode, input.ModelPattern, input.MonthlyTokenQuota, enabled)
	if err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	_ = h.service.Reload(r.Context())
	apiresponse.OK(w, item)
}

func (h *HTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.require(w, r, identity.PermissionPricingManage); !ok {
		return
	}
	if err := h.service.Delete(r.Context(), r.PathValue("quota_id")); err != nil {
		apiresponse.Error(w, http.StatusBadRequest, err.Error())
		return
	}
	_ = h.service.Reload(r.Context())
	apiresponse.OK(w, map[string]bool{"deleted": true})
}

var _ = strings.TrimSpace
