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

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

func (l *GetMessageRecordsByIdLogic) GetMessageRecordsById(req *types.IDReq) (*types.MessageRecordsInfoResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, err := l.svcCtx.DB.MessageRecords.Query().
		Where(
			messagerecords.IDEQ(req.Id),                   // Filter by ID
			messagerecords.OrganizationID(organizationId), // Additional filter by organizationId
		).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.MessageRecordsInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.MessageRecordsInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:      &data.Status,
			BotWxid:     &data.BotWxid,
			ContactId:   &data.ContactID,
			ContactType: &data.ContactType,
			ContactWxid: &data.ContactWxid,
			ContentType: &data.ContentType,
			Content:     &data.Content,
			ErrorDetail: &data.ErrorDetail,
			SendTime:    pointy.GetUnixMilliPointer(data.SendTime.UnixMilli()),
			SourceType:  &data.SourceType,
			SourceId:    &data.SourceID,
			SubSourceId: &data.SubSourceID,
		},
	}, nil
}
