package batch_msg

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/batchmsg"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StopBatchMsgLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStopBatchMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StopBatchMsgLogic {
	return &StopBatchMsgLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *StopBatchMsgLogic) StopBatchMsg(req *types.IDReq) (resp *types.BaseMsgResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	batchMsg, err := l.svcCtx.DB.BatchMsg.Query().Where(batchmsg.ID(req.Id), batchmsg.OrganizationID(organizationId)).First(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, errorx.NewInvalidArgumentError("群发消息不存在")
		}
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	if batchMsg.Status == 0 {
		// 设置状态为3，代表已停止
		err = l.svcCtx.DB.BatchMsg.UpdateOneID(batchMsg.ID).SetStatus(3).Exec(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	} else if batchMsg.Status == 3 {
		return nil, errorx.NewInvalidArgumentError("群发消息已停止")
	} else if batchMsg.Status == 2 {
		return nil, errorx.NewInvalidArgumentError("群发消息已发送完毕，无法停止")
	} else if batchMsg.Status == 1 {
		return nil, errorx.NewInvalidArgumentError("群发消息正在发送中，无法停止")
	}

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
