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

package notification

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

// 标记已读
func NewReadNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReadNotificationLogic {
	return &ReadNotificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ReadNotificationLogic) ReadNotification(req *types.PathId) (resp *types.EmptyResp, err error) {
	uid, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	current, err := l.svcCtx.NotificationRpc.GetNotificationsById(l.ctx, &notificationservice.GetNotificationsByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	if current.GetNotifications() == nil {
		return nil, errors.New("notification not found")
	}
	if current.GetNotifications().GetUserId() != uid {
		return nil, errors.New("notification not found")
	}

	read := true
	now := time.Now().Unix()
	_, err = l.svcCtx.NotificationRpc.UpdateNotifications(l.ctx, &notificationservice.UpdateNotificationsReq{
		Id:        req.Id,
		Read:      &read,
		UpdatedAt: &now,
	})
	if err != nil {
		return nil, err
	}

	return &types.EmptyResp{}, nil
}
