// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package notification

import (
	"context"

	"juwan-backend/app/notification/api/internal/svc"
	"juwan-backend/app/notification/api/internal/types"
	"juwan-backend/app/notification/rpc/notificationservice"
	"juwan-backend/common/utils/contextj"

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

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

// 获取通知列表
func NewListNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListNotificationsLogic {
	return &ListNotificationsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListNotificationsLogic) ListNotifications(req *types.PageReq) (resp *types.NotificationListResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	limit := req.Limit
	if limit <= 0 {
		limit = 20
	}

	out, err := l.svcCtx.NotificationRpc.SearchNotifications(l.ctx, &notificationservice.SearchNotificationsReq{
		Offset: req.Offset,
		Limit:  limit,
		UserId: &uid,
	})
	if err != nil {
		return nil, err
	}
	items := make([]types.Notification, 0, len(out.GetNotifications()))
	for _, item := range out.GetNotifications() {
		items = append(items, toAPINotification(item))
	}

	return &types.NotificationListResp{
		Items: items,
		Meta: types.PageMeta{
			Total:  int64(len(items)),
			Offset: req.Offset,
			Limit:  limit,
		},
	}, nil
}
