<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Client\ConnectCpCreationClient;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class ConnectBasicInstagramUserIdType extends AbstractType
{
    private readonly array $choices;

    public function __construct(ConnectCpCreationClient $client)
    {
        $choices = [];

        $result = $client->get('/api/client_socials', [
            'query' => [
                'network' => 'basic_instagram',
            ],
        ]);

        $data = json_decode($result->getBody()->getContents(), true) ?: [];
        $members = $data['hydra:member'] ?? [];

        foreach ($members as $member) {
            $label = mb_trim(($member['username'] ?? '').' '.($member['email'] ?? ''));
            $id = $member['id'] ?? null;

            if ('' !== $label && null !== $id) {
                $choices[$label] = $id;
            }
        }

        $this->choices = $choices;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'choices' => $this->choices,
            'multiple' => false,
            'placeholder' => 'Sélectionner…',
            'attr' => [
                'class' => 'select2',
            ],
        ]);
    }

    public function getParent(): string
    {
        return ChoiceType::class;
    }
}
