package message_records

import (
	"context"
	"wechat-api/ent/messagerecords"
	"wechat-api/ent/predicate"
	"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 GetMessageRecordsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetMessageRecordsListLogic) GetMessageRecordsList(req *types.MessageRecordsListReq) (*types.MessageRecordsListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.MessageRecords
	// 按机构ID搜
	predicates = append(predicates, messagerecords.OrganizationIDEQ(organizationId))
	// 按群发ID搜
	if req.BatchMsgId != nil {
		predicates = append(predicates, messagerecords.SourceIDEQ(*req.BatchMsgId))
	}
	if req.SourceType != nil {
		predicates = append(predicates, messagerecords.SourceTypeEQ(*req.SourceType))
	}
	if req.SourceId != nil {
		predicates = append(predicates, messagerecords.SourceIDEQ(*req.SourceId))
	}
	if req.BotWxid != nil {
		predicates = append(predicates, messagerecords.BotWxidContains(*req.BotWxid))
	}
	if req.Status != nil {
		predicates = append(predicates, messagerecords.StatusEQ(*req.Status))
	}
	data, err := l.svcCtx.DB.MessageRecords.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

	resp := &types.MessageRecordsListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.MessageRecordsInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: &v.ID,
				},
				Status:      &v.Status,
				BotWxid:     &v.BotWxid,
				ContactWxid: &v.ContactWxid,
				ContactType: &v.ContactType,
				Content:     &v.Content,
				ErrorDetail: &v.ErrorDetail,
				SendTime:    pointy.GetUnixMilliPointer(v.SendTime.UnixMilli()),
			})
	}

	return resp, nil
}
