<?php

namespace AIPT\Api\AutomationJobs;

/**
 * IncrementalProgressTracker
 *
 * Replaces expensive COUNT/SUM progress calculation with incremental counters.
 *
 * @since 2.3.0
 */
class IncrementalProgressTracker {
    /** @var \wpdb */
    private $wpdb;
    /** @var string */
    private $jobs_table;

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

    /**
     * Increment processed and failed counters atomically and recompute progress.
     *
     * @param int $job_id
     * @param int $processed_inc
     * @param int $failed_inc
     * @return bool
     */
    public function increment($job_id, $processed_inc, $failed_inc = 0) {
        $job_id = (int) $job_id;
        $p = max(0, (int) $processed_inc);
        $f = max(0, (int) $failed_inc);

        $now = current_time('mysql');

        $sql = $this->wpdb->prepare(
            "UPDATE {$this->jobs_table}
             SET processed_products = processed_products + %d,
                 failed_products = failed_products + %d,
                 progress = LEAST(100, ROUND(((processed_products + %d) / GREATEST(1, total_products)) * 100)),
                 updated_at = %s,
                 last_progress_logged_at = %s
             WHERE id = %d",
            $p,
            $f,
            $p,
            $now,
            $now,
            $job_id
        );

        $res = $this->wpdb->query($sql);
        return $res !== false;
    }
}

