package admin

import (
	"github.com/gofiber/fiber/v2"

	configapp "github.com/break/junhong_cmp_fiber/internal/application/systemconfig"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	configquery "github.com/break/junhong_cmp_fiber/internal/query/systemconfig"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

// SystemConfigHandler 提供受控系统配置查询和单 Key 更新接口。
type SystemConfigHandler struct {
	listQuery     *configquery.ListQuery
	updateService *configapp.UpdateService
}

// NewSystemConfigHandler 创建系统配置 Handler。
func NewSystemConfigHandler(listQuery *configquery.ListQuery, updateService *configapp.UpdateService) *SystemConfigHandler {
	return &SystemConfigHandler{listQuery: listQuery, updateService: updateService}
}

// List 查询受控系统配置列表。
// GET /api/admin/system-configs
func (h *SystemConfigHandler) List(c *fiber.Ctx) error {
	var request dto.SystemConfigListRequest
	if err := c.QueryParser(&request); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	result, err := h.listQuery.Execute(c.UserContext(), request)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

// Update 更新一个已注册且允许修改的系统配置。
// PUT /api/admin/system-configs/:key
func (h *SystemConfigHandler) Update(c *fiber.Ctx) error {
	key := c.Params("key")
	if key == "" {
		return errors.New(errors.CodeInvalidParam)
	}
	var request dto.UpdateSystemConfigRequest
	if err := c.BodyParser(&request); err != nil {
		return errors.New(errors.CodeInvalidParam)
	}
	result, err := h.updateService.Execute(c.UserContext(), key, request)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}
