<?php

defined('ABSPATH') || exit;

/**
 * Job to update member data in batches.
 *
 * @property integer $limit The batch limit.
 */
class MeprUpdateMemberDataJob extends MeprBaseJob
{
    /**
     * Perform this job.
     */
    public function perform()
    {
        MeprMigrator::before_start();

        $processor = new class ($this->limit ?? 10) extends MeprBatchMigrator {
            /**
             * Fetches the next batch of users who need their member data updated.
             *
             * This is a cursorless batcher (it declares no cursor_column()), so
             * the base relies on this source set shrinking as users are written:
             * termination depends on get_update_all_member_data_user_ids()
             * eventually returning an empty array. The query must keep excluding
             * already-updated users, or the batch loop never terminates.
             *
             * @return array
             */
            protected function fetch_batch(): array
            {
                return MeprUser::get_update_all_member_data_user_ids(true, $this->limit);
            }
        };

        while ($processor->next_batch()) {
            $user_ids = $processor->get_items();

            foreach ($user_ids as $user_id) {
                MeprUser::update_member_data_static($user_id);
            }
        }

        MeprMigrator::finish();

        if ($processor->has_items()) {
            $job        = new MeprUpdateMemberDataJob();
            $job->limit = $processor->get_limit();
            $job->enqueue();
        }
    }
}
