<?php

namespace Modules\Additional\Specifique\Client13\Modules\Stock\Validator;

use Entity\Model\Dilispec;
use Exception;
use Helpers\Trad\ITrad;
use Modules\Stock\Enum\TypeBonEntreeEnum;
use Modules\Stock\Repository\DilispecRepo;
use PDO;

class BonEntreeValidatorSpecifique
{
    /**
     * @param array<string,mixed> $enteEntity
     * @param array<int,array<string,mixed>> $lignEntities
     * @return array<string, array<int<0, max>, array<string,mixed>>>
     * @throws Exception
     */
    public static function validate(PDO $pdo, ITrad $trad, array $enteEntity, array $lignEntities): array
    {
        $dilispec = new Dilispec($pdo);
        $dilispecRepo = new DilispecRepo($pdo);
        $isTiersInterne = $dilispec->find(['TYPEDICO' => 'SEMTIERINT', 'CODEDICO' => $enteEntity['PROV']]);

        if ($enteEntity['TYPE_BE'] === TypeBonEntreeEnum::R->name) {
            if ($isTiersInterne) {
                foreach ($lignEntities as $lignEntity) {
                    if ($dilispecRepo->countRubriqueForLigneImputations($enteEntity, $lignEntity) === 0) {
                        $nonBloquantErrors[] = [
                            'id' => $lignEntity['NO_LIG_BE'],
                            'message' => $trad->t('Imputations non conformes à la rubrique de l\'article, ou pas d\'imputations paramétrées pour la rubrique'),
                            'type' => 'Non bloquant'
                        ];
                    }
                }
            } else {
                foreach ($lignEntities as $lignEntity) {
                    if ($dilispecRepo->countForLigneImputations($enteEntity, $lignEntity) === 0) {
                        $nonBloquantErrors[] = [
                            'id' => $lignEntity['NO_LIG_BE'],
                            'message' => $trad->t('Cette association d\'imputation n\'est pas autorisée'),
                            'type' => 'Non bloquant'
                        ];
                    }
                }
            }
        }
        if ($enteEntity['TYPE_BE'] === TypeBonEntreeEnum::E->name) {
            foreach ($lignEntities as $lignEntity) {
                if (empty($dilispecRepo->getImputationParametrage($enteEntity, $lignEntity))) {
                    $nonBloquantErrors[] = [
                        'id' => $lignEntity['NO_LIG_BE'],
                        'message' => $trad->t('Imputations non conformes à la rubrique de l\'article'),
                        'type' => 'Non bloquant'
                    ];
                }
            }
        }

        return [
            'nonBloquantErrors' => $nonBloquantErrors??[],
        ];
    }
}
