package runners

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

// AcpEventsPurgeRepo is the minimal repo surface this runner needs.
// internal/acp.Repository satisfies it via an adapter in app.go.
type AcpEventsPurgeRepo interface {
	PurgeEventsBefore(ctx context.Context, before time.Time) (int64, error)
}

// AcpEventsPurge deletes acp_events older than retention. Periodic; idempotent.
type AcpEventsPurge struct {
	repo      AcpEventsPurgeRepo
	retention time.Duration
	log       *slog.Logger
}

// NewAcpEventsPurge builds the purger.
func NewAcpEventsPurge(repo AcpEventsPurgeRepo, retention time.Duration, log *slog.Logger) *AcpEventsPurge {
	if log == nil {
		log = slog.Default()
	}
	return &AcpEventsPurge{repo: repo, retention: retention, log: log}
}

// Run purges once.
func (r *AcpEventsPurge) Run(ctx context.Context) {
	cutoff := time.Now().Add(-r.retention)
	rows, err := r.repo.PurgeEventsBefore(ctx, cutoff)
	if err != nil {
		r.log.Error("acp_events.purge", "err", err.Error())
		return
	}
	if rows > 0 {
		r.log.Info("acp_events.purged", "count", rows, "before", cutoff.UTC().Format(time.RFC3339))
	}
}
