<?php

declare(strict_types=1);

namespace App\Service\Cron\Job;

use App\Service\Cron\BaseCronJob;
use App\Service\Doctrine\SchemaValidation\DiffTypeEnum;
use App\Service\Doctrine\SchemaValidation\SchemaValidationService;
use JetBrains\PhpStorm\Pure;

/**
 * Valide le schéma Doctrine en le comparant à la V1.
 *
 * >>> ot:cron run schema-validation --preview
 * >>> ot:cron run schema-validation
 */
class SchemaValidation extends BaseCronJob
{
    public const VALIDATION_FILTER = DiffTypeEnum::MISSING_RELATION;

    #[Pure]
    public function __construct(
        private readonly SchemaValidationService $schemaValidationService,
    ) {
        parent::__construct();
    }

    /**
     * @return array<string>
     */
    protected function getDiffAsCsv(): array
    {
        $diff = $this->schemaValidationService->validateSchema(self::VALIDATION_FILTER);

        return $this->schemaValidationService->formatToCsv($diff);
    }

    /**
     * Validate the doctrine schema (without reporting).
     */
    public function preview(): void
    {
        $csv = $this->getDiffAsCsv();

        if (empty($csv)) {
            $this->ui->print('No difference found');
        } else {
            foreach ($csv as $line) {
                $this->ui->print($line);
            }
            $this->ui->print('');
            $this->ui->print('> '.count($csv).' differences found');
        }
    }

    /**
     * Validate the doctrine schema and report.
     */
    public function execute(): void
    {
        $csv = $this->getDiffAsCsv();

        if (empty($csv)) {
            $this->logger->info('No difference found');
        } else {
            foreach ($csv as $line) {
                $this->logger->warning($line);
            }
            $this->logger->warning(count($csv).' differences found');
        }
    }
}
