<?php
/**
 * Retention cleanup.
 *
 * @package CertaCart_EU_Product_Readiness
 */

namespace CertaCart\EU_Product_Readiness;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Retention operates on the plugin's dedicated scan table and requires current rows.

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Cleanup {
	public const HOOK = 'ccpr_daily_cleanup';

	public static function register(): void {
		add_action( self::HOOK, array( __CLASS__, 'run' ) );
		if ( ! wp_next_scheduled( self::HOOK ) ) {
			self::schedule();
		}
	}

	public static function schedule(): void {
		if ( ! wp_next_scheduled( self::HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
		}
	}

	public static function run(): void {
		global $wpdb;
		$retain = max( 1, (int) Settings::get( 'retention_scans', 10 ) );
		$table   = Schema::scans_table();
		$all_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT id FROM %i WHERE status NOT IN ('queued','running') ORDER BY id DESC LIMIT 500 OFFSET %d",
				$table,
				$retain
			)
		);
		$ids = is_array( $all_ids ) ? $all_ids : array();
		$repo    = new Scan_Repository();
		foreach ( $ids as $id ) {
			$repo->delete_scan( absint( $id ) );
		}
	}
}
