package infra

import (
	"fmt"
	"time"
)

// JobCleanup deletes jobs in terminal states (completed, failed, dead) that are
// older than olderThan. Returns the number of rows deleted.
// This is useful for keeping the jobs table small in long-running applications.
func JobCleanup(q *JobQueue, olderThan time.Duration) (int64, error) {
	if q == nil {
		return 0, fmt.Errorf("job_cleanup: queue must not be nil")
	}

	cutoff := time.Now().UTC().Add(-olderThan).Format(time.RFC3339)

	query := fmt.Sprintf(`
DELETE FROM %s
WHERE status IN ('completed', 'failed', 'dead')
  AND created_at < ?
`, q.TableName)

	res, err := q.DB.Exec(query, cutoff)
	if err != nil {
		return 0, fmt.Errorf("job_cleanup: delete: %w", err)
	}
	n, err := res.RowsAffected()
	if err != nil {
		return 0, fmt.Errorf("job_cleanup: rows affected: %w", err)
	}
	return n, nil
}
