<?php

namespace App\Service\Frontend;

use Symfony\Contracts\HttpClient\HttpClientInterface;
use Psr\Log\LoggerInterface;
use App\Kernel;

class ListmonkMailerService
{
    private string $baseUrl;
    private string $api_user;
    private string $token;

    public function __construct(
        private Kernel $kernel,
        private readonly HttpClientInterface $httpClient,
        private readonly LoggerInterface $logger,
    ) {
        $container = $kernel->getContainer();
        $this->baseUrl = $container->getParameter('listmonk.base_url');
        $this->api_user = $container->getParameter('listmonk.api_user');
        $this->token = $container->getParameter('listmonk.token');
    }

    /**
     * Envoie un email transactionnel via Listmonk.
     * @param string $toEmails     Adresse du destinataire
     * @param int    $templateId  ID du template dans Listmonk
     * @param array  $data        Variables injectées dans le template ({{ .Tx.Data.name }})
     * @param string $subscriber  external
     * @param array  $headers     Headers mail optionnels (Reply-To, etc.)
     */
    public function send(
        array $toEmails, 
        int $templateId, 
        array $data = [], 
        string $subscriber = 'external',
        array $headers = ['Content-Type' => 'application/json; charset=utf-8']
        ): bool {


        try {
            $response = $this->httpClient->request('POST', $this->baseUrl . '/api/tx', [
                'auth_basic' => [$this->api_user, $this->token],
                'headers' => $headers,
                'json' => [                               // équivalent de --data-binary avec JSON
                    'subscriber_mode' => $subscriber,
                    'subscriber_emails' => $toEmails,
                    'template_id' => $templateId,
                    'data' => $data,
                    'content_type' => 'html',
                ],
            ]);
            if ($response->getStatusCode() === 200) {
                return true;
            }

            $this->logger->error('Listmonk TX error', [
                'status' => $response->getStatusCode(),
                'body'   => $response->getContent(false),
            ]);

            return false;

        } catch (\Throwable $e) {
            $this->logger->error('Listmonk exception: ' . $e->getMessage());
            return false;
        }
    }


    
}