<?php

namespace Myvetshop\Module\Clinique\Form\Admin\Product;

use Myvetshop\Module\Clinique\Entity\MyvetshopClinique;
use Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository;
use PrestaShop\PrestaShop\Core\Form\FormDataProviderInterface;

class BlockProductDataProvider implements FormDataProviderInterface
{
    protected MyvetshopCliniqueRepository $cliniqueRepository;

    public function __construct(
        MyvetshopCliniqueRepository $cliniqueRepository
    ) {
        $this->cliniqueRepository = $cliniqueRepository;
    }

    /**
     * {@inheritdoc}
     *
     * @return array{product_id: ?int, code_privileges: ?string}
     */
    public function getData(): array
    {
        return [
            'product_id' => null,
            'code_privileges' => null,
        ];
    }

    /**
     * {@inheritdoc}
     *
     * @param array{product_id: ?int, code_privileges: ?string} $data
     *
     * @return array<array{key: string, domain: string, parameters: array<string>}>
     */
    public function setData(array $data): array
    {
        // This form doesn't need to save any data, so it only validates the data
        return $this->validate($data);
    }

    /**
     * Perform validations on form data.
     *
     * @param array{product_id?: ?int, code_privileges?: ?string} $data
     *
     * @return array<array{key: string, domain: string, parameters: array<string>}>
     */
    private function validate(array $data): array
    {
        $errors = [];

        $product = new \Product(\intval($data['product_id'] ?? null));
        if (!\Validate::isLoadedObject($product)) {
            $errors[] = [
                'key' => 'Invalid product ID : %product_id%',
                'domain' => 'Admin.Orderscustomers.Notification',
                'parameters' => [
                    '%product_id%' => \strval($data['product_id'] ?? ''),
                ],
            ];
        }

        $codePrivileges = \array_filter(
            \array_unique(
                \array_map(
                    'trim',
                    \explode("\n", $data['code_privileges'] ?? '')
                ),
            )
        );
        $cliniques = $this->cliniqueRepository->findAllByPrivilegedCode($codePrivileges);
        if (\count($cliniques) !== \count($codePrivileges)) {
            $foundCodes = \array_map(
                static function (MyvetshopClinique $clinique) {
                    return $clinique->codePrivilege;
                },
                $cliniques
            );

            $errors[] = [
                'key' => 'Invalid privilege codes : %codes%',
                'domain' => 'Admin.Orderscustomers.Notification',
                'parameters' => ['%codes%' => \implode(',', \array_diff($codePrivileges, $foundCodes))],
            ];
        }

        return $errors;
    }
}
