package logic

import (
	"context"
	"errors"

	"juwan-backend/app/notification/rpc/internal/models/notifications"
	"juwan-backend/app/notification/rpc/internal/svc"
	"juwan-backend/app/notification/rpc/pb"

	"entgo.io/ent/dialect/sql"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *SearchNotificationsLogic) SearchNotifications(in *pb.SearchNotificationsReq) (*pb.SearchNotificationsResp, error) {
	limit := in.GetLimit()
	if limit <= 0 {
		limit = 20
	}
	if limit > 100 {
		return nil, errors.New("limit too large")
	}
	offset := in.GetOffset()
	if offset < 0 {
		offset = 0
	}

	query := l.svcCtx.NotificationModelRO.Notifications.Query()
	if in.Id != nil {
		query = query.Where(notifications.IDEQ(in.GetId()))
	}
	if in.UserId != nil {
		query = query.Where(notifications.UserIDEQ(in.GetUserId()))
	}
	if in.Type != nil {
		query = query.Where(notifications.TypeEQ(in.GetType()))
	}
	if in.Read != nil {
		query = query.Where(notifications.ReadEQ(in.GetRead()))
	}

	list, err := query.
		Order(notifications.ByCreatedAt(sql.OrderDesc()), notifications.ByID(sql.OrderDesc())).
		Offset(int(offset)).
		Limit(int(limit)).
		All(l.ctx)
	if err != nil {
		logx.Errorf("searchNotifications err: %v", err)
		return nil, errors.New("search notifications failed")
	}

	out := make([]*pb.Notifications, len(list))
	for i, n := range list {
		out[i] = entNotificationToPb(n)
	}

	return &pb.SearchNotificationsResp{Notifications: out}, nil
}
