package auth

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

// NewVerifierWithRetry waits for the OIDC provider (e.g. Authentik blueprints) to become ready.
func NewVerifierWithRetry(ctx context.Context, issuerURL, clientID, discoveryHost string, attempts int, delay time.Duration) (*Verifier, error) {
	if issuerURL == "" || clientID == "" {
		return nil, nil
	}
	if attempts < 1 {
		attempts = 1
	}

	var lastErr error
	for i := 1; i <= attempts; i++ {
		verifier, err := NewVerifier(ctx, issuerURL, clientID, discoveryHost)
		if err == nil {
			if i > 1 {
				slog.Info("OIDC verifier ready", "attempt", i)
			}
			return verifier, nil
		}
		lastErr = err
		if i == attempts {
			break
		}
		slog.Warn("OIDC verifier not ready, retrying",
			"attempt", i,
			"max", attempts,
			"error", err,
		)
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-time.After(delay):
		}
	}
	return nil, lastErr
}
