package portal

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

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

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/models", h.models)
	h.mux.HandleFunc("GET /api/v1/admin/model-requests", h.requests)
	h.mux.HandleFunc("POST /api/v1/admin/model-requests/{id}/approve", h.decide("approved"))
	h.mux.HandleFunc("POST /api/v1/admin/model-requests/{id}/reject", h.decide("rejected"))
	return h
}
func (h *AdminHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }
func (h *AdminHTTPHandler) admin(w http.ResponseWriter, r *http.Request) (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, identity.PermissionProviderRead) {
		apiresponse.Error(w, 403, "缺少模型查看权限")
		return a, false
	}
	return a, true
}
func (h *AdminHTTPHandler) models(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.admin(w, r); !ok {
		return
	}
	items, err := h.service.Models(r.Context())
	if err != nil {
		portalError(w, err)
		return
	}
	apiresponse.OK(w, items)
}
func (h *AdminHTTPHandler) requests(w http.ResponseWriter, r *http.Request) {
	if _, ok := h.admin(w, r); !ok {
		return
	}
	status := strings.TrimSpace(r.URL.Query().Get("status"))
	if status != "" && status != "pending" && status != "approved" && status != "rejected" && status != "cancelled" {
		apiresponse.Error(w, 400, "状态无效")
		return
	}
	items, err := h.service.ModelRequests(r.Context(), "", status)
	if err != nil {
		portalError(w, err)
		return
	}
	apiresponse.OK(w, items)
}
func (h *AdminHTTPHandler) decide(status string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		a, ok := h.admin(w, r)
		if !ok {
			return
		}
		if !identity.HasPermission(a, identity.PermissionProviderManage) {
			apiresponse.Error(w, 403, "缺少模型审批权限")
			return
		}
		var input struct {
			Note string `json:"note"`
		}
		decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
		if err := decoder.Decode(&input); err != nil && !errors.Is(err, http.ErrBodyReadAfterClose) {
			apiresponse.Error(w, 400, "请求格式无效")
			return
		}
		item, err := h.service.DecideModelRequest(r.Context(), r.PathValue("id"), status, input.Note, a.ID)
		if err != nil {
			portalError(w, err)
			return
		}
		apiresponse.OK(w, item)
	}
}
