package handler

import (
	"kra/internal/service"
	"kra/internal/service/dto"

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

type Parameter struct {
	service *service.ParameterService
}

func NewParameter(service *service.ParameterService) *Parameter {
	return &Parameter{service: service}
}

func (h *Parameter) Create(c *gin.Context) {
	var req dto.SystemParameterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.CreateParameterRequest(c.Request.Context(), &req); err != nil {
		Fail(c, "创建失败:"+err.Error())
		return
	}
	Write(c, CodeSuccess, gin.H{}, "创建成功")
}

func (h *Parameter) Update(c *gin.Context) {
	var req dto.SystemParameterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.UpdateParameterRequest(c.Request.Context(), &req); err != nil {
		Fail(c, "更新失败:"+err.Error())
		return
	}
	Write(c, CodeSuccess, gin.H{}, "更新成功")
}

func (h *Parameter) Delete(c *gin.Context) {
	if err := h.service.DeleteParameters(c.Request.Context(), []string{c.Query("ID")}); err != nil {
		Fail(c, "删除失败:"+err.Error())
		return
	}
	Write(c, CodeSuccess, gin.H{}, "删除成功")
}

func (h *Parameter) DeleteMany(c *gin.Context) {
	ids := c.QueryArray("IDs[]")
	if err := h.service.DeleteParameters(c.Request.Context(), ids); err != nil {
		Fail(c, "批量删除失败:"+err.Error())
		return
	}
	Write(c, CodeSuccess, gin.H{}, "批量删除成功")
}

func (h *Parameter) Find(c *gin.Context) {
	item, err := h.service.ParameterByID(c.Request.Context(), c.Query("ID"))
	if err != nil {
		Fail(c, "查询失败:"+err.Error())
		return
	}
	OKWithData(c, item)
}

func (h *Parameter) Get(c *gin.Context) {
	item, err := h.service.ParameterByKey(c.Request.Context(), c.Query("key"))
	if err != nil {
		Fail(c, "获取失败:"+err.Error())
		return
	}
	Write(c, CodeSuccess, item, "获取成功")
}

func (h *Parameter) List(c *gin.Context) {
	var req dto.SystemParameterSearchRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	items, total, err := h.service.ParametersFilter(c.Request.Context(), req.Page, req.PageSize, req.Name, req.Key, req.StartCreatedAt, req.EndCreatedAt)
	if err != nil {
		Fail(c, "获取失败:"+err.Error())
		return
	}
	Write(c, CodeSuccess, PageResult{List: items, Total: total, Page: req.Page, PageSize: req.PageSize}, "获取成功")
}
