package logic

import (
	"context"
	"errors"

	"juwan-backend/app/notification/rpc/internal/svc"
	"juwan-backend/app/notification/rpc/pb"
	"juwan-backend/app/snowflake/rpc/snowflake"

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

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

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

func (l *AddNotificationsLogic) AddNotifications(in *pb.AddNotificationsReq) (*pb.AddNotificationsResp, error) {
	if in.GetUserId() <= 0 {
		return nil, errors.New("userId is required")
	}
	if in.GetType() == "" {
		return nil, errors.New("type is required")
	}
	if in.GetTitle() == "" {
		return nil, errors.New("title is required")
	}
	if in.GetContent() == "" {
		return nil, errors.New("content is required")
	}

	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		return nil, errors.New("create notification id failed")
	}

	created, err := l.svcCtx.NotificationModelRW.Notifications.Create().
		SetID(idResp.Id).
		SetUserID(in.GetUserId()).
		SetType(in.GetType()).
		SetTitle(in.GetTitle()).
		SetContent(in.GetContent()).
		SetNillableLink(in.Link).
		Save(l.ctx)
	if err != nil {
		logx.Errorf("addNotifications err: %v", err)
		return nil, errors.New("add notification failed")
	}

	return &pb.AddNotificationsResp{Id: created.ID}, nil
}
