<?php

/**
 * Example: Creating a Custom Recurring Job
 * 
 * This shows how to create a job that implements RecurringJobInterface
 * for dynamic control over recurring behavior.
 */

namespace console\jobs;

use Yii;
use yii\base\BaseObject;
use PortalPeople\queues\RecurringJobInterface;

/**
 * Example Recurring Job with Dynamic Control
 * 
 * This job can control its own recurring interval and continuation
 * based on runtime conditions.
 */
class SmartRecurringJob extends BaseObject implements RecurringJobInterface
{
    public $minInterval = 300;      // 5 minutes
    public $maxInterval = 3600;     // 1 hour
    public $workThreshold = 100;     // Items to process before continuing
    
    /**
     * Execute the job logic.
     * 
     * @param \common\components\Queue\Queue $queue
     * @return void
     */
    public function execute($queue)
    {
        // Your job logic here
        $itemsProcessed = $this->processData();
        
        Yii::info("Processed {$itemsProcessed} items", __METHOD__);
        
        // Store data for next run decision
        Yii::$app->cache->set('smart_job_last_count', $itemsProcessed, 7200);
    }
    
    /**
     * Dynamically adjust interval based on workload.
     * Heavy load = shorter interval, light load = longer interval.
     * 
     * @return int Seconds until next run
     */
    public function getRecurringInterval()
    {
        $lastCount = Yii::$app->cache->get('smart_job_last_count') ?? 0;
        
        if ($lastCount > $this->workThreshold) {
            // Heavy load - run more frequently
            return $this->minInterval;
        } elseif ($lastCount > 50) {
            // Medium load
            return 1800; // 30 minutes
        } else {
            // Light load - run less frequently
            return $this->maxInterval;
        }
    }
    
    /**
     * Decide whether to continue recurring.
     * Could check time of day, system load, feature flags, etc.
     * 
     * @return bool
     */
    public function shouldContinue()
    {
        // Example: Only run during business hours (8 AM - 6 PM)
        $hour = (int) date('H');
        if ($hour < 8 || $hour >= 18) {
            Yii::info("Outside business hours, pausing recurring job", __METHOD__);
            return false;
        }
        
        // Example: Check feature flag
        if (!Yii::$app->params['features']['smartJobEnabled'] ?? true) {
            Yii::info("Feature disabled, stopping recurring job", __METHOD__);
            return false;
        }
        
        // Continue by default
        return true;
    }
    
    /**
     * Process data (example implementation).
     * 
     * @return int Number of items processed
     */
    protected function processData()
    {
        // Your actual processing logic here
        // This is just an example
        
        $items = []; // Get items from database/API/etc
        $count = 0;
        
        foreach ($items as $item) {
            // Process each item
            $count++;
        }
        
        return $count;
    }
    
    /**
     * Optional: Define TTR based on expected workload.
     * 
     * @return int
     */
    public function getTtr()
    {
        return 600; // 10 minutes
    }
    
    /**
     * Optional: Define retry logic.
     * 
     * @param int $attempt
     * @param \Exception $error
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        // Retry up to 3 times, but not for certain errors
        if ($error instanceof \yii\db\Exception) {
            return false; // Don't retry database errors
        }
        
        return $attempt < 3;
    }
}
