package message_records

import (
	"context"
	"wechat-api/ent/messagerecords"

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

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *UpdateMessageRecordsLogic) UpdateMessageRecords(req *types.MessageRecordsInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	err := l.svcCtx.DB.MessageRecords.UpdateOneID(*req.Id).
		Where(messagerecords.OrganizationID(organizationId)).
		SetNotNilStatus(req.Status).
		SetNotNilBotWxid(req.BotWxid).
		SetNotNilContactID(req.ContactId).
		SetNotNilContactType(req.ContactType).
		SetNotNilContactWxid(req.ContactWxid).
		SetNotNilContentType(req.ContentType).
		SetNotNilContent(req.Content).
		SetNotNilErrorDetail(req.ErrorDetail).
		SetNotNilSendTime(pointy.GetTimeMilliPointer(req.SendTime)).
		SetNotNilSourceType(req.SourceType).
		SetNotNilSourceID(req.SourceId).
		SetNotNilSubSourceID(req.SubSourceId).
		Exec(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

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