<?php

namespace App\Service\Cron\Job;

use App\Service\Cron\BaseCronJob;
use App\Service\Cron\CronjobInterface;
use App\Service\Dolibarr\DolibarrSyncService;
use JetBrains\PhpStorm\Pure;

/**
 * Push the latest data from the Opentalent DB to dolibarr
 *
 * >>> ot:cron dolibarr-sync
 */
class DolibarrSync extends BaseCronJob implements CronjobInterface
{
    /**
     * How many operations are shown each time the preview choice is made
     */
    public const PREVIEW_CHUNK = 20;

    #[Pure]
    public function __construct(
        private DolibarrSyncService $dolibarrSyncService
    ) {
        parent::__construct();
    }

    /**
     * Previews the sync operation without actually modifying anything
     *
     * @throws \Exception
     */
    public function preview(): void
    {
        $operations = $this->dolibarrSyncService->scan(function($i, $total) { $this->ui->progress($i, $total); });

        foreach ($operations as $i => $iValue) {
            $this->ui->print($i . '. ' . $iValue->getLabel());
            foreach ($iValue->getChangeLog() as $message) {
                $this->ui->print('   ' . $message);
            }
        }
    }

    /**
     * Executes the sync
     *
     * @throws \Exception
     */
    public function execute(): void
    {
        $operations = $this->dolibarrSyncService->scan(function($i, $total) { $this->ui->progress($i, $total); });

        $this->ui->print("Executing...");

        $operations = $this->dolibarrSyncService->execute($operations, function($i, $total) { $this->ui->progress($i, $total); });

        $successes = count(array_filter($operations, static function ($o) { return $o->getStatus() === $o::STATUS_DONE; } ));
        $errors = count(array_filter($operations, static function ($o) { return $o->getStatus() === $o::STATUS_ERROR; } ));
        $this->ui->print($successes . " operations successfully executed");
        $this->ui->print($errors . " errors");
    }
}
