<?php

namespace KupShop\FeedsBundle\Inspection;

use KupShop\SystemInspectionBundle\Inspections\Inspection;
use KupShop\SystemInspectionBundle\Inspections\User\UserInspectionInterface;
use KupShop\SystemInspectionBundle\InspectionWriters\MessageTypes\SimpleMessage;

class NotGeneratingFeedInspection extends Inspection implements UserInspectionInterface
{
    protected function fetchNotGeneratingFeeds(): array
    {
        $feeds = sqlQueryBuilder()->select('f.name')
            ->from('feeds', 'f')
            ->where('active = 1 AND regenerated IS NOT NULL AND last_download > NOW() - INTERVAL 2 DAY AND regenerated < last_download - INTERVAL 2 DAY')
            ->execute()->fetchFirstColumn();

        return $feeds;
    }

    public function runInspection(): ?array
    {
        $errors = [];

        $notGeneratingFeeds = $this->fetchNotGeneratingFeeds();
        if (count($notGeneratingFeeds) > 0) {
            $errors[] = new SimpleMessage(
                sprintf(
                    translate('notGeneratingFeedsError', 'feedsInspection', false, true),
                    implode(', ', $notGeneratingFeeds)
                )
            );
        }

        return $errors;
    }
}
