<?php
/**
 * sync-user-interests (hourly)
 *
 * Ships running tallies from wp_af_user_interests. Watermarked on
 * last_engaged so we resend updated rows when their counts have changed,
 * not just newly-inserted ones.
 */

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

require_once __DIR__ . '/class-sync-base.php';

class AF_Interests_Sync extends AF_Sync_Base {

    protected $endpoint     = 'sync-user-interests';
    protected $cron_hook    = 'auctionforge_sync_user_interests';
    protected $cron_schedule = 'hourly';
    protected $batch_size   = 500;
    protected $health_key   = 'user-interests';

    protected function read_batch() {
        global $wpdb;
        $table = $wpdb->prefix . 'af_user_interests';
        if (!$this->table_exists($table)) return array();

        $watermark = get_option('auctionforge_interests_sync_watermark', '2000-01-01 00:00:00');

        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE last_engaged >= %s ORDER BY last_engaged ASC, id ASC LIMIT %d",
            $watermark, $this->batch_size
        ), ARRAY_A);
    }

    protected function build_payload($rows) {
        return array('records' => $rows);
    }

    protected function mark_synced($rows, $response) {
        if (empty($rows)) return;
        $latest = end($rows);
        if (!empty($latest['last_engaged'])) {
            update_option('auctionforge_interests_sync_watermark', $latest['last_engaged'], 'no');
        }
    }
}
