package runners

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

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

// AcpTurnsPurge deletes acp_turns older than retention. Periodic; idempotent.
type AcpTurnsPurge struct {
	repo      AcpTurnsPurgeRepo
	retention time.Duration
	log       *slog.Logger
}

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

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