<?php

namespace auctionforge\inc\sync;

use auctionforge\inc\import\AuctionList;
use auctionforge\inc\import\LotList;

/**
 * BulkSyncWorker
 *
 * Processes full re-sync jobs for upcoming and past auctions. This is the
 * queued/observable equivalent of the synchronous re_sync_action handler at
 * inc/controllers/AuctionsAPI.php (importBidSpiritUpcoming / importBidSpiritPast):
 *
 *   1. AuctionList::init()  — refresh the auction taxonomy from BidSpirit
 *   2. LotList::init($upcoming) — iterate matching auctions, refresh lots
 *
 * The worker exposes the active job id as a global so LotList::auctionProcessing()
 * can call SyncQueue::heartbeat() between auctions and avoid being auto-failed
 * by the safety cron's stale-job timeout during long bulk runs.
 */
class BulkSyncWorker
{
    public static function process($job)
    {
        $upcoming = ($job->job_type === SyncQueue::TYPE_FULL_SYNC_UPCOMING);
        $label = $upcoming ? 'upcoming' : 'past';
        $errors = array();
        $lotsProcessed = 0;
        $start = microtime(true);

        SyncLogger::log('worker', "▶ Starting full re-sync ({$label})", 'info', null, $job->id);

        // Expose the active job id so LotList::auctionProcessing() can heartbeat.
        $GLOBALS['af_bulk_sync_job_id'] = (int) $job->id;

        try {
            // Stage 1: refresh auction list from BidSpirit
            SyncLogger::log('worker', "  [1/2] Refreshing auction list…", 'info', null, $job->id);
            $auctionList = new AuctionList();
            $auctionList->init();
            SyncQueue::heartbeat($job->id);

            $alErrors = $auctionList->getErrors();
            if (!empty($alErrors)) {
                $errors = array_merge($errors, (array) $alErrors);
                SyncLogger::log('worker', "  [1/2] AuctionList completed with " . count($alErrors) . " errors", 'warning', null, $job->id);
            } else {
                SyncLogger::log('worker', "  [1/2] AuctionList refreshed", 'info', null, $job->id);
            }

            // Stage 2: re-import lots for every auction of this kind
            SyncLogger::log('worker', "  [2/2] Re-importing lots ({$label})…", 'info', null, $job->id);
            $lotList = new LotList();
            $lotList->setPriority(2);
            $lotList->init($upcoming);

            $llErrors = $lotList->getErrors();
            if (!empty($llErrors)) {
                $errors = array_merge($errors, (array) $llErrors);
                SyncLogger::log('worker', "  [2/2] LotList completed with " . count($llErrors) . " errors", 'warning', null, $job->id);
            }

            // Pull a rough lots-processed count from LotList logs if available
            if (method_exists($lotList, 'getLoggedInfo')) {
                foreach ((array) $lotList->getLoggedInfo() as $info) {
                    if (isset($info['new_records'])) {
                        $lotsProcessed += (int) $info['new_records'];
                    }
                }
            }
        } finally {
            $GLOBALS['af_bulk_sync_job_id'] = null;
        }

        $duration = round(microtime(true) - $start, 1);
        SyncLogger::log(
            'worker',
            "Full re-sync ({$label}) finished in {$duration}s · {$lotsProcessed} lots staged · " . count($errors) . " errors",
            empty($errors) ? 'success' : 'warning',
            null,
            $job->id
        );

        return array(
            'errors'         => $errors,
            'lots_processed' => $lotsProcessed,
        );
    }
}
