package support import ( "context" "errors" "fmt" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) // ListNotifications returns in-app support notifications for a user (newest first). func (s *Service) ListNotifications(ctx context.Context, userID uuid.UUID, unreadOnly bool, limit, offset int) ([]Notification, int64, error) { where := `n.user_id = $1` args := []any{userID} if unreadOnly { where += ` AND n.read_at IS NULL` } var total int64 if err := s.Pool.QueryRow(ctx, `SELECT count(*) FROM support_notifications n WHERE `+where, args...).Scan(&total); err != nil { return nil, 0, err } args = append(args, limit, offset) q := fmt.Sprintf(` SELECT n.id, n.user_id, n.ticket_id, n.message_id, n.kind, n.read_at, n.created_at, COALESCE(t.subject, '') FROM support_notifications n LEFT JOIN support_tickets t ON t.id = n.ticket_id WHERE %s ORDER BY n.created_at DESC LIMIT $%d OFFSET $%d`, where, len(args)-1, len(args)) rows, err := s.Pool.Query(ctx, q, args...) if err != nil { return nil, 0, err } defer rows.Close() out := make([]Notification, 0) for rows.Next() { var n Notification if err := rows.Scan(&n.ID, &n.UserID, &n.TicketID, &n.MessageID, &n.Kind, &n.ReadAt, &n.CreatedAt, &n.Subject); err != nil { return nil, 0, err } out = append(out, n) } return out, total, rows.Err() } // UnreadNotificationCount returns unread support notification count for the bell badge. func (s *Service) UnreadNotificationCount(ctx context.Context, userID uuid.UUID) (int64, error) { var n int64 err := s.Pool.QueryRow(ctx, ` SELECT count(*) FROM support_notifications WHERE user_id = $1 AND read_at IS NULL`, userID).Scan(&n) return n, err } // MarkNotificationRead marks one notification owned by the user as read. func (s *Service) MarkNotificationRead(ctx context.Context, userID, notificationID uuid.UUID) error { tag, err := s.Pool.Exec(ctx, ` UPDATE support_notifications SET read_at = now() WHERE id = $1 AND user_id = $2 AND read_at IS NULL`, notificationID, userID) if err != nil { return err } if tag.RowsAffected() == 0 { var exists bool err = s.Pool.QueryRow(ctx, ` SELECT EXISTS(SELECT 1 FROM support_notifications WHERE id = $1 AND user_id = $2)`, notificationID, userID).Scan(&exists) if err != nil { return err } if !exists { return ErrNotificationGone } } return nil } // MarkAllNotificationsRead marks all unread notifications for the user as read. func (s *Service) MarkAllNotificationsRead(ctx context.Context, userID uuid.UUID) (int64, error) { tag, err := s.Pool.Exec(ctx, ` UPDATE support_notifications SET read_at = now() WHERE user_id = $1 AND read_at IS NULL`, userID) if err != nil { return 0, err } return tag.RowsAffected(), nil } // ErrIsNoRows exposes pgx.ErrNoRows for tests without importing pgx elsewhere. func ErrIsNoRows(err error) bool { return errors.Is(err, pgx.ErrNoRows) }