package runners

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

// JobsPurgeRepo is the minimal repo surface for purge.
type JobsPurgeRepo interface {
	PurgeCompleted(ctx context.Context, completedBefore time.Time) (int64, error)
}

// JobPurge deletes completed/dead jobs older than retention. Periodic; idempotent.
type JobPurge struct {
	repo      JobsPurgeRepo
	retention time.Duration
	log       *slog.Logger
}

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

// Run purges once.
func (p *JobPurge) Run(ctx context.Context) {
	cutoff := time.Now().Add(-p.retention)
	rows, err := p.repo.PurgeCompleted(ctx, cutoff)
	if err != nil {
		p.log.Error("job_purge.purge", "err", err.Error())
		return
	}
	if rows > 0 {
		p.log.Info("job_purge.purged", "count", rows)
	}
}
