<?php

namespace Myvetshop\Module\Clinique\Command\Clinic;

use Myvetshop\Module\Clinique\Clinic\ClinicEmailRedirectionManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class ClinicImportEmailsCommand extends Command
{
    protected ClinicEmailRedirectionManager $redirectionManager;

    protected function configure(): void
    {
        $this->setDescription("Importe les e-mais (email_original) des cliniques depuis l'API Ovh");
    }

    public function __construct(
        ClinicEmailRedirectionManager $redirectionManager
    ) {
        $this->redirectionManager = $redirectionManager;

        parent::__construct('app:clinic:import-emails');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // Deactivate caching
        \Module::getInstanceByName('myvetshopclinique');
        \Cache::setInstanceForTesting(new \NoOpCache());
        \Db::getInstance()->disableCache();

        $styledOutput = new SymfonyStyle($input, $output);

        $clinics = \Clinique::getAll();

        $progressBar = new ProgressBar($styledOutput, \count($clinics));

        foreach ($clinics as $i => $clinic) {
            $progressBar->setProgress($i);

            if ($clinic->deleted) {
                continue;
            }

            $email = \strval($this->redirectionManager->getRedirection($clinic->code_privilege));

            if ($clinic->email_original !== $email) {
                $clinic->email_original = $email;
                $clinic->save();
            }
        }

        $progressBar->finish();

        return 0;
    }
}
