package message_records

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

	"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 CreateMessageRecordsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *CreateMessageRecordsLogic) CreateMessageRecords(req *types.MessageRecordsInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	meta := custom_types.Meta{}
	if req.Meta != nil {
		meta.Filename = req.Meta.Filename
	}

	_, err := l.svcCtx.DB.MessageRecords.Create().
		SetNotNilStatus(req.Status).
		SetNotNilBotWxid(req.BotWxid).
		SetNotNilContactID(req.ContactId).
		SetNotNilContactType(req.ContactType).
		SetNotNilContactWxid(req.ContactWxid).
		SetNotNilContentType(req.ContentType).
		SetNotNilContent(req.Content).
		SetMeta(meta).
		SetNotNilErrorDetail(req.ErrorDetail).
		SetNotNilSendTime(pointy.GetTimeMilliPointer(req.SendTime)).
		SetNotNilSourceType(req.SourceType).
		SetNotNilSourceID(req.SourceId).
		SetNotNilSubSourceID(req.SubSourceId).
		SetOrganizationID(organizationId).
		Save(l.ctx)

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

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