<?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\FtpDownloadService;

class DownloadFilesJob 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 download job', 'indicator.jobs');

            return;
        }

        $inboxDir = Yii::getAlias('@runtime/indicator/inbox');
        if (!is_dir($inboxDir)) {
            @mkdir($inboxDir, 0755, true);
        }

        $service = new FtpDownloadService([
            'protocol' => $module->protocol,
            'host' => $module->ftpHost,
            'port' => $module->ftpPort,
            'username' => $module->ftpUser,
            'password' => $module->ftpPassword,
            'remotePath' => $module->ftpPath,
            'deleteAfterDownload' => $module->deleteAfterDownload,
            'inboxPath' => $inboxDir,
        ]);

        $result = $service->download();

        Yii::info("Indicator download job completed. Downloaded: " . count($result['downloaded']) .
            ", Errors: " . count($result['errors']), 'indicator.jobs');

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

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

        return $module?->downloadInterval ?? 3600;
    }

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