<?php
/**
 * Daily cleanup of snapshots past their retention window.
 *
 * @package EmberPrice
 */

namespace EmberPrice\Core;

defined( 'ABSPATH' ) || exit;

/**
 * SPEC §6's snapshot retention: a recurring Action Scheduler action that
 * deletes `embp_snapshots` rows older than a configurable window (default
 * 30 days, the `embp_snapshot_retention_days` option). Lives in Core (not
 * Rest) because, unlike the batch schedulers, it isn't wired to a REST
 * route or product-domain logic -- it only touches other Core classes
 * (Settings, Snapshots).
 */
final class SnapshotRetention {

	/**
	 * Action Scheduler hook name for the recurring cleanup.
	 */
	public const HOOK = 'embp_snapshot_retention_cleanup';

	/**
	 * Action Scheduler group, mostly for the admin UI (Tools > Scheduled Actions).
	 */
	private const GROUP = 'emberprice';

	private const DEFAULT_RETENTION_DAYS = 30;

	/**
	 * Typed settings accessor, for the configurable retention window.
	 *
	 * @var Settings
	 */
	private Settings $settings;

	/**
	 * Snapshot data access.
	 *
	 * @var Snapshots
	 */
	private Snapshots $snapshots;

	/**
	 * Constructor.
	 *
	 * @param Settings|null  $settings  Defaults to a new instance.
	 * @param Snapshots|null $snapshots Defaults to a new instance.
	 */
	public function __construct( ?Settings $settings = null, ?Snapshots $snapshots = null ) {
		$this->settings  = $settings ?? new Settings( Crypto::for_site() );
		$this->snapshots = $snapshots ?? new Snapshots();
	}

	/**
	 * Wires the Action Scheduler hook to run(). Call once, from the
	 * composition root, on every request (Action Scheduler may invoke it
	 * from a cron/async request that never touches wp-admin or REST).
	 */
	public function register_hook(): void {
		add_action( self::HOOK, array( $this, 'run' ) );
	}

	/**
	 * Schedules the recurring daily cleanup, unless one is already scheduled.
	 */
	public function schedule(): void {
		if ( false === as_next_scheduled_action( self::HOOK, array(), self::GROUP ) ) {
			as_schedule_recurring_action( time(), DAY_IN_SECONDS, self::HOOK, array(), self::GROUP, true );
		}
	}

	/**
	 * Action Scheduler callback: deletes snapshots past the configured
	 * retention window.
	 */
	public function run(): void {
		$this->snapshots->delete_older_than(
			$this->settings->get_int( 'snapshot_retention_days', self::DEFAULT_RETENTION_DAYS )
		);
	}
}
