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

package notification

import (
	"context"
	"time"

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

// 全部已读
func NewReadAllNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReadAllNotificationsLogic {
	return &ReadAllNotificationsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ReadAllNotificationsLogic) ReadAllNotifications(req *types.EmptyResp) (resp *types.EmptyResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	unread := false
	out, err := l.svcCtx.NotificationRpc.SearchNotifications(l.ctx, &notificationservice.SearchNotificationsReq{
		Offset: 0,
		Limit:  100,
		UserId: &uid,
		Read:   &unread,
	})
	if err != nil {
		return nil, err
	}
	read := true
	now := time.Now().Unix()
	for _, item := range out.GetNotifications() {
		_, err = l.svcCtx.NotificationRpc.UpdateNotifications(l.ctx, &notificationservice.UpdateNotificationsReq{
			Id:        item.GetId(),
			Read:      &read,
			UpdatedAt: &now,
		})
		if err != nil {
			return nil, err
		}
	}

	return &types.EmptyResp{}, nil
}
