package app

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/validation"
	"mini-chat/internal/repository/mysql/model"
)

type deleteAppRequest struct {
	Ids string `json:"ids" binding:"required"` // 小程序编号(多个用,分割)
}

type deleteAppResponse struct {
	Message string `json:"message"` // 提示信息
}

// DeleteApp 删除小程序
// @Summary 删除小程序
// @Description 删除小程序
// @Tags 管理端.小程序
// @Accept json
// @Produce json
// @Param RequestBody body deleteAppRequest true "请求参数"
// @Success 200 {object} deleteAppResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/app/delete [post]
// @Security LoginVerifyToken
func (h *handler) DeleteApp() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(deleteAppRequest)
		res := new(deleteAppResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.CreateAppError,
				fmt.Sprintf("%s: %s", code.Text(code.CreateAppError), "禁止操作")),
			)
			return
		}

		idList := strings.Split(req.Ids, ",")
		if len(idList) == 0 || (len(idList) == 1 && idList[0] == "") {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"小程序编号不能为空"),
			)
			return
		}

		var ids []int32

		for _, strID := range idList {
			if strID == "" {
				continue
			}

			id, err := strconv.Atoi(strID)
			if err != nil {
				ctx.AbortWithError(core.Error(
					http.StatusBadRequest,
					code.ParamBindError,
					fmt.Sprintf("无效的小程序编号: %s", strID)),
				)
				return
			}

			ids = append(ids, int32(id))
		}

		if len(ids) == 0 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"小程序编号不能为空"),
			)
			return
		}

		if _, err := h.writeDB.MiniProgram.WithContext(ctx.RequestContext()).
			Where(h.writeDB.MiniProgram.ID.In(ids...)).
			Delete(&model.MiniProgram{}); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.DeleteAppError,
				fmt.Sprintf("%s: %s", code.Text(code.DeleteAppError), err.Error())),
			)
			return
		}
		res.Message = "操作成功"
		ctx.Payload(res)
	}
}
