package repositories import ( "errors" "fmt" "attune-heart-therapy/internal/models" "gorm.io/gorm" ) // notificationRepository implements the NotificationRepository interface type notificationRepository struct { db *gorm.DB } // NewNotificationRepository creates a new instance of NotificationRepository func NewNotificationRepository(db *gorm.DB) NotificationRepository { return ¬ificationRepository{ db: db, } } // Create creates a new notification in the database func (r *notificationRepository) Create(notification *models.Notification) error { if notification == nil { return errors.New("notification cannot be nil") } if err := r.db.Create(notification).Error; err != nil { return fmt.Errorf("failed to create notification: %w", err) } return nil } // GetByID retrieves a notification by its ID with user and booking preloaded func (r *notificationRepository) GetByID(id uint) (*models.Notification, error) { if id == 0 { return nil, errors.New("invalid notification ID") } var notification models.Notification if err := r.db.Preload("User").Preload("Booking").First(¬ification, id).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, fmt.Errorf("notification with ID %d not found", id) } return nil, fmt.Errorf("failed to get notification by ID: %w", err) } return ¬ification, nil } // Update updates an existing notification in the database func (r *notificationRepository) Update(notification *models.Notification) error { if notification == nil { return errors.New("notification cannot be nil") } if notification.ID == 0 { return errors.New("notification ID is required for update") } // Check if notification exists var existingNotification models.Notification if err := r.db.First(&existingNotification, notification.ID).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return fmt.Errorf("notification with ID %d not found", notification.ID) } return fmt.Errorf("failed to check notification existence: %w", err) } // Update the notification if err := r.db.Save(notification).Error; err != nil { return fmt.Errorf("failed to update notification: %w", err) } return nil } // GetPendingNotifications retrieves all notifications that are ready to be sent func (r *notificationRepository) GetPendingNotifications() ([]models.Notification, error) { var notifications []models.Notification if err := r.db.Preload("User").Preload("Booking"). Where("status = ? AND (scheduled_at IS NULL OR scheduled_at <= NOW())", models.NotificationStatusPending). Order("created_at ASC"). Find(¬ifications).Error; err != nil { return nil, fmt.Errorf("failed to get pending notifications: %w", err) } return notifications, nil }