package server

import (
	"context"
	"log/slog"
	"time"
)

const (
	appNotificationExpiryInterval  = 10 * time.Second
	appNotificationExpiryBatchSize = 100
)

func (srv *Server) runAppNotificationExpiryWorker(ctx context.Context) {
	if srv == nil || srv.stores == nil || srv.stores.App == nil {
		return
	}
	srv.runAppNotificationExpiryPass(ctx)
	ticker := time.NewTicker(appNotificationExpiryInterval)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			srv.runAppNotificationExpiryPass(ctx)
		}
	}
}

func (srv *Server) runAppNotificationExpiryPass(ctx context.Context) {
	result, err := srv.stores.App.ExpireDueAppNotifications(
		ctx,
		schedulerWorkspaceGroupIDForConfig(srv.config.Server),
		time.Now().UTC(),
		appNotificationExpiryBatchSize,
	)
	if err != nil {
		if srv.logger != nil && ctx.Err() == nil {
			srv.logger.WarnContext(ctx, "App notification expiry sweep failed", slog.Any("error", err))
		}
		return
	}
	if srv.logger != nil {
		for _, failure := range result.Failures {
			srv.logger.WarnContext(ctx, "App notification expiry candidate did not converge",
				slog.String("workspace_id", failure.WorkspaceID),
				slog.String("notification_id", failure.NotificationID),
				slog.Any("error", failure.Error),
			)
		}
	}
}
