<?php

namespace Opentalent\OtAdmin\Controller;

use Opentalent\OtAdmin\Domain\Entity\ScanReport;
use Opentalent\OtCore\Controller\ActionController;
use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * ScanController scan the Typo3 DB to find potential issues
 */
class ScanController extends ActionController
{
    public function __construct(
        private readonly SiteController $siteController,
        private readonly OrganizationRepository $organizationRepository
    ) {
        parent::__construct();
    }

    /**
     * Perform a full scan of the Typo3 DB, and confront it to the
     * Opentalent organizations list.
     *
     * @param bool $fullScan If true, a 'warnings' entry will be added to the result of each site status,
     *                        and a full scan of the website pages will be performed.
     * @param callable|null $progressCallback Expects a function that takes 2 parameters : the current step, and the max
     * @return ScanReport
     */
    public function scanAllAction(bool $fullScan = false, ?callable $progressCallback = null): ScanReport
    {
        $report = new ScanReport();

        $organizationsCollection = $this->organizationRepository->getAll();
        $i = 0;
        $total = count($organizationsCollection->getMembers());

        foreach ($organizationsCollection->getMembers() as $organization) {
            $i++;

            $status = $this->siteController->getSiteStatusAction($organization->getId(), $fullScan);

            $report->setResultFor($organization->getId(), $status);

            if ($progressCallback !== null) {
                $progressCallback($i, $total);
            }
        }

        return $report;
    }
}
