package cprelation

import (
	"errors"
	"fmt"

	"hyapp-admin-server/internal/appctx"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/response"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *Service
	audit   shared.OperationLogger
}

func New(userDB DB, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(userDB), audit: audit}
}

func (h *Handler) GetConfig(c *gin.Context) {
	config, err := h.service.GetConfig(c.Request.Context(), appctx.FromContext(c.Request.Context()))
	if err != nil {
		response.ServerError(c, "获取CP配置失败")
		return
	}
	response.OK(c, config)
}

func (h *Handler) UpdateConfig(c *gin.Context) {
	var req updateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "CP配置参数不正确")
		return
	}
	config, err := h.service.UpdateConfig(c.Request.Context(), appctx.FromContext(c.Request.Context()), req)
	if err != nil {
		if errors.Is(err, ErrInvalidArgument) {
			response.BadRequest(c, err.Error())
			return
		}
		response.ServerError(c, "更新CP配置失败")
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "update-cp-config", "user_cp_relation_configs", config.AppCode, "success",
		fmt.Sprintf("relations=%d", len(config.Relations)))
	response.OK(c, config)
}
