package notification import ( "context" "time" "tm/pkg/logger" orm "tm/pkg/mongo" "tm/pkg/response" "go.mongodb.org/mongo-driver/v2/bson" ) // NotificationRepository defines the interface for notification data operations type NotificationRepository interface { Create(ctx context.Context, notification *Notification) error Update(ctx context.Context, notification *Notification) error Get(ctx context.Context, id string) (*Notification, error) Search(ctx context.Context, form *SearchForm, pagination *response.Pagination) ([]Notification, int64, error) Delete(ctx context.Context, id string) error } // notificationRepository implements NotificationRepository interface type notificationRepository struct { ormRepo orm.Repository[Notification] logger logger.Logger } func collection() string { return "notifications" } // NewNotificationRepository creates a new notification repository func NewNotificationRepository(mongoManager *orm.ConnectionManager, logger logger.Logger) NotificationRepository { // Create indexes using the ORM's index management indexes := []orm.Index{ *orm.CreateTextIndex("search_idx", "title", "description"), } // Create indexes err := mongoManager.CreateIndexes(collection(), indexes) if err != nil { logger.Warn("Failed to create customer indexes", map[string]interface{}{ "error": err.Error(), }) } ormRepo := orm.NewRepository[Notification](mongoManager.GetCollection(collection()), logger) return ¬ificationRepository{ ormRepo: ormRepo, logger: logger, } } // Create creates a new notification func (r *notificationRepository) Create(ctx context.Context, notification *Notification) error { notification.SetCreatedAt(time.Now().Unix()) return r.ormRepo.Create(ctx, notification) } // Create creates a new notification func (r *notificationRepository) Update(ctx context.Context, notification *Notification) error { notification.SetUpdatedAt(time.Now().Unix()) return r.ormRepo.Update(ctx, notification) } // Get gets a notification by id func (r *notificationRepository) Get(ctx context.Context, id string) (*Notification, error) { return r.ormRepo.FindByID(ctx, id) } // Search searches for notifications func (r *notificationRepository) Search(ctx context.Context, form *SearchForm, pagination *response.Pagination) ([]Notification, int64, error) { // Build pagination paginationBuilder := orm.NewPaginationBuilder(). Limit(pagination.Limit). Skip(pagination.Offset). SortBy(pagination.SortBy, pagination.SortOrder) filter := bson.M{} if form.Search != nil { filter["$text"] = bson.M{"$search": *form.Search} } // Use ORM to find customers result, err := r.ormRepo.FindAll(ctx, filter, paginationBuilder.Build()) if err != nil { r.logger.Error("Failed to search customers", map[string]interface{}{ "error": err.Error(), "search": form.Search, }) return nil, 0, err } return result.Items, result.TotalCount, nil } // Delete deletes a notification func (r *notificationRepository) Delete(ctx context.Context, id string) error { return r.ormRepo.Delete(ctx, id) }