package app

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

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

	"gorm.io/gorm"
)

type createAppRequest 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 createAppResponse struct {
	Message string `json:"message"` // 提示信息
}

// CreateApp 新增小程序
// @Summary 新增小程序
// @Description 新增小程序
// @Tags 管理端.小程序
// @Accept json
// @Produce json
// @Param RequestBody body createAppRequest true "请求参数"
// @Success 200 {object} createAppResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/app/create [post]
// @Security LoginVerifyToken
func (h *handler) CreateApp() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createAppRequest)
		res := new(createAppResponse)
		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
		}

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

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

		App := new(model.MiniProgram)
		App.AppID = req.AppID
		App.AppSecret = req.AppSecret
		App.Name = req.Name
		App.Description = req.Description
		App.Avatar = req.Avatar
		App.TemplateID = req.TemplateID
		App.CreatedUser = ctx.SessionUserInfo().UserName
		App.CreatedAt = time.Now()
		if err := h.writeDB.MiniProgram.WithContext(ctx.RequestContext()).Create(App); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.CreateAppError,
				fmt.Sprintf("%s: %s", code.Text(code.CreateAppError), err.Error())),
			)
			return
		}

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