package app

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

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/validation"

	"gorm.io/gorm"
)

type modifyAppRequest struct {
	AppID       string `json:"app_id" binding:"required"`     // 小程序ID
	AppSecret   string `json:"app_secret" binding:"required"` // 小程序密钥
	Name        string `json:"name" binding:"required"`       // 名称
	Description string `json:"description"`                   // 描述
	Avatar      string `json:"avatar"`                        // 头像
	TemplateID  string `json:"template_id"`                   // 模版ID
}

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

// ModifyApp 编辑小程序
// @Summary 编辑小程序
// @Description 编辑小程序
// @Tags 管理端.小程序
// @Accept json
// @Produce json
// @Param id path string true "编号ID"
// @Param RequestBody body modifyAppRequest true "请求参数"
// @Success 200 {object} modifyAppResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/app/{id} [put]
// @Security LoginVerifyToken
func (h *handler) ModifyApp() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(modifyAppRequest)
		res := new(modifyAppResponse)
		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
		}

		if req.AppID == "" && req.Name == "" {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"小程序ID和标题不能为空"),
			)
			return
		}

		id, err := strconv.Atoi(ctx.Param("id"))
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"未传递编号ID"),
			)
			return
		}

		checkIdInfo, err := h.readDB.MiniProgram.WithContext(ctx.RequestContext()).
			Where(h.readDB.MiniProgram.ID.Eq(int32(id))).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAppError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAppError), err.Error())),
			)
			return
		}

		if checkIdInfo == nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAppError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAppError), "该小程序不存在")),
			)
			return
		}

		checkAppIDInfo, err := h.readDB.MiniProgram.WithContext(ctx.RequestContext()).
			Where(h.readDB.MiniProgram.ID.Neq(int32(id))).
			Where(h.readDB.MiniProgram.AppID.Eq(req.AppID)).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAppError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAppError), err.Error())),
			)
			return
		}

		if checkAppIDInfo != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAppError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAppError), "该小程序ID已存在")),
			)
			return
		}

		checkIdInfo.AppID = req.AppID
		checkIdInfo.AppSecret = req.AppSecret
		checkIdInfo.Name = req.Name
		checkIdInfo.Description = req.Description
		checkIdInfo.Avatar = req.Avatar
		checkIdInfo.TemplateID = req.TemplateID
		checkIdInfo.UpdatedUser = ctx.SessionUserInfo().UserName
		checkIdInfo.UpdatedAt = time.Now()
		if err := h.writeDB.MiniProgram.WithContext(ctx.RequestContext()).Save(checkIdInfo); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAppError,
				fmt.Sprintf("%s：%s", code.Text(code.ModifyAppError), err.Error())),
			)
			return
		}

		res.Message = "操作成功"
		ctx.Payload(res)
	}
}
