<?php

namespace AIPT\Core\Database;

/**
 * Periodic cleanup of expired rate-limit counter rows.
 *
 * Rows whose window has closed (window_start + window_seconds < NOW()) are
 * safe to delete; the next INSERT will recreate them as needed.
 *
 * Follows the same pattern as JobLogCleaner for consistency.
 *
 * @since 2.6.0
 */
class RateLimiterCleaner {

    const CRON_HOOK = 'aipt_cleanup_rate_limits';

    private $table;

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'aipt_rate_limit_counters';
    }

    /**
     * Schedule the daily cleanup cron job.
     *
     * @return bool Whether scheduling succeeded.
     */
    public function schedule(): bool {
        try {
            if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
                return false;
            }

            if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
                $scheduled = wp_schedule_event( time(), 'daily', self::CRON_HOOK );
                if ( false === $scheduled ) {
                    return false;
                }
            }

            return true;
        } catch ( \Exception $e ) {
            return false;
        }
    }

    /**
     * Unschedule the cleanup cron job.
     *
     * @return bool Whether unscheduling succeeded.
     */
    public function unschedule(): bool {
        try {
            $timestamp = wp_next_scheduled( self::CRON_HOOK );
            if ( $timestamp ) {
                $unscheduled = wp_unschedule_event( $timestamp, self::CRON_HOOK );
                if ( false === $unscheduled ) {
                    return false;
                }
            }

            return true;
        } catch ( \Exception $e ) {
            return false;
        }
    }

    /**
     * Delete rate-limit rows whose window has expired.
     *
     * Uses UNIX_TIMESTAMP() for server-side time comparison to avoid
     * clock-skew issues between PHP and MySQL.
     *
     * @return int|false Number of deleted rows or false on error.
     */
    public function clean_expired_rows() {
        global $wpdb;

        try {

            return $wpdb->query(
                $wpdb->prepare(
                    'DELETE FROM %i WHERE window_start + window_seconds < UNIX_TIMESTAMP()',
                    $this->table
                )
            );
        } catch ( \Exception $e ) {
            return false;
        }
    }

    public static function cron_callback(): void {
        try {
            $cleaner = new self();
            $cleaner->clean_expired_rows();
        } catch ( \Exception $e ) {

        }
    }
}
