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"
)

type adminSendMessageRequest struct {
	AppID    string `json:"app_id" binding:"required"`     // 小程序ID
	ToUserID string `json:"to_user_id" binding:"required"` // 接收用户ID
	MsgType  int32  `json:"msg_type" binding:"required"`   // 消息类型(1:文本 2:图片)
	Content  string `json:"content" binding:"required"`    // 内容
}

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

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

		createData := new(model.AppMessageLog)
		createData.AppID = req.AppID
		createData.SenderID = "888888"
		createData.SenderName = "平台"
		createData.Content = req.Content
		createData.ReceiverID = req.ToUserID
		createData.MsgType = req.MsgType
		createData.SendTime = time.Now()
		createData.CreatedAt = time.Now()
		if err := h.writeDB.AppMessageLog.WithContext(ctx.RequestContext()).Create(createData); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.SendMessageError,
				fmt.Sprintf("%s: %s", code.Text(code.SendMessageError), err.Error()),
			))
		}

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