<?php

namespace PortalPeople\indicator\jobs;

use Yii;
use yii\queue\JobInterface;
use PortalPeople\queues\RecurringJobInterface;
use PortalPeople\queues\RecurringJobWrapper;
use PortalPeople\indicator\Module;
use PortalPeople\indicator\services\ProcessFilesService;

class ProcessFilesJob implements JobInterface, RecurringJobInterface
{
    public $recurringJob = true;

    public function execute($queue)
    {
        /** @var Module $module */
        $module = Yii::$app->getModule('indicator');

        if (!$module || !$module->isConfigured()) {
            Yii::warning('Indicator module not configured, skipping process job', 'indicator.jobs');

            return;
        }

        $inboxDir = Yii::getAlias('@runtime/indicator/inbox');
        $processedDir = Yii::getAlias('@runtime/indicator/processed');
        $failedDir = Yii::getAlias('@runtime/indicator/failed');

        foreach ([$inboxDir, $processedDir, $failedDir] as $dir) {
            if (!is_dir($dir)) {
                @mkdir($dir, 0755, true);
            }
        }

        $service = new ProcessFilesService([
            'inboxPath' => $inboxDir,
            'processedPath' => $processedDir,
            'failedPath' => $failedDir,
            'module' => $module,
        ]);

        $result = $service->process();

        Yii::info("Indicator process job completed. Processed: {$result['processed']}, " .
            "Created: {$result['created']}, Failed: {$result['failed']}", 'indicator.jobs');

        if (!empty($result['errors'])) {
            Yii::warning('Indicator process errors: ' . json_encode($result['errors']), 'indicator.jobs');
        }
    }

    public function getRecurringInterval(): int
    {
        $module = Yii::$app->getModule('indicator');

        return $module?->processInterval ?? 7200;
    }

    public function shouldReschedule(): bool
    {
        return true;
    }
}
