<?php

namespace Modules\Stock\Service\Form;

use Entity\Model\Memos;
use Entity\Model\Sarticle;
use Exception;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Sql;
use Modules\Stock\Interface\FormServiceInterface;
use Modules\Stock\Trait\FormTrait;
use PDO;

readonly class StockArticleFormService implements FormServiceInterface
{
    use FormTrait;

    public function __construct(private PDO $pdo)
    {
    }

    /**
     * @param array<string,mixed> $post
     * @param array<string,mixed> $data
     * @return array<string,mixed>
     */
    public function initEntity(array $post, array $data = []): array
    {
        $post['NM_DESCR'] = $data['MEMOS']['NODEMEMO'];

        return $post;
    }

    /**
     * @throws Exception
     * @param array<string,mixed> $entity
     */
    public function flushData(array $entity, array $post = []): void
    {
        $this->pdo->beginTransaction();

        (new Memos($this->pdo))->merge($post['MEMOS']);
        (new Sarticle($this->pdo))->processAndMerge($entity);
        ChampSupp::updateCS($post, $this->pdo);

        $this->pdo->commit();
    }

    /**
     * @param array<string,mixed> $memos
     * @return array<string,mixed>
     */
    public function updateMemos(array $memos): array
    {
        $sqlMemo = new Sql();
        $memos['NODEMEMO'] = $memos['NODEMEMO'] === '' ? $sqlMemo->generateNum($this->pdo): $memos['NODEMEMO'];

        return $memos;
    }
}
