<?php

namespace AIPT\Core\Database;

/**
 * Periodic cleanup of old job log records to prevent unbounded table growth.
 *
 * Follows the same pattern as HistoryCleaner for consistency.
 *
 * @since 2.7.0
 */
class JobLogCleaner {

    /**
     * Cron hook name.
     */
    const CRON_HOOK = 'aipt_clean_job_logs';

    /**
     * Retention period in days.
     *
     * Completed job logs older than this are automatically deleted.
     */
    const RETENTION_DAYS = 30;

    /**
     * Job logs table name.
     *
     * @var string
     */
    private $table;

    /**
     * Constructor.
     */
    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'aipt_job_logs';
    }

    /**
     * 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 job log records older than the retention period.
     *
     * Deletes ALL logs older than the retention threshold regardless of
     * parent job status. The job_logs table has no status column, so
     * filtering by job state would require a JOIN to aipt_automation_jobs.
     * In practice, jobs older than 30 days are expected to be terminal.
     *
     * @return int|false Number of deleted records or false on error.
     */
    public function clean_old_records() {
        global $wpdb;

        try {
            $date_threshold = gmdate( 'Y-m-d H:i:s', strtotime( '-' . self::RETENTION_DAYS . ' days' ) );

            $query = $wpdb->prepare(

                "DELETE FROM {$this->table} WHERE created_at < %s",
                $date_threshold
            );

            return $wpdb->query( $query );
        } catch ( \Exception $e ) {
            return false;
        }
    }

    /**
     * Static cron callback.
     *
     * Errors are swallowed to prevent cron failures from blocking other tasks.
     */
    public static function cron_callback(): void {
        try {
            $cleaner = new self();
            $cleaner->clean_old_records();
        } catch ( \Exception $e ) {

        }
    }
}
