<?php

declare(strict_types=1);

namespace App\Infrastructure\Api;

use App\Framework\Api\ApiRequestTrait;
use App\Framework\Http\Method;
use App\Framework\HttpClient\AuthConfig;
use App\Framework\HttpClient\ClientOptions;
use App\Framework\HttpClient\CurlHttpClient;
use App\Framework\HttpClient\HttpClient;

final class RapidMailClient
{
    use ApiRequestTrait;

    public function __construct(
        string $username,
        string $password,
        ?HttpClient $httpClient = null
    ) {
        $this->baseUrl = 'https://apiv3.emailsys.net/v1';
        $this->defaultOptions = new ClientOptions(
            auth: AuthConfig::basic($username, $password)
        );
        $this->httpClient = $httpClient ?? new CurlHttpClient();
    }

    /**
     * Fügt einen Empfänger zu einer Mailingliste hinzu
     */
    public function addRecipient(string $name, string $email, int $recipientlistId): array
    {
        $response = $this->sendRequest(
            method: Method::POST,
            endpoint: 'recipients',
            data: [
                'firstname' => $name,
                'email' => $email,
                'recipientlist_id' => $recipientlistId,
            ],
            options: $this->defaultOptions->with([
                'query' => [
                    'send_activationmail' => 'yes',
                    'test_mode' => 'yes',
                ],
            ])
        );

        return $this->decodeJson($response);
    }

    /**
     * Löscht einen Empfänger aus einer Mailingliste
     */
    public function deleteRecipient(int $recipientId): void
    {
        $this->sendRequest(
            method: Method::DELETE,
            endpoint: "recipients/{$recipientId}"
        );
    }

    /**
     * Ruft die Mailinglisten ab
     */
    public function getRecipientLists(): array
    {
        $response = $this->sendRequest(
            method: Method::GET,
            endpoint: 'recipientlists'
        );

        return $this->decodeJson($response);
    }

    /**
     * Sucht nach Empfängern in einer Mailingliste
     */
    public function searchRecipients(string $email, int $recipientlistId): array
    {
        $response = $this->sendRequest(
            method: Method::GET,
            endpoint: 'recipients',
            data: [
                'filter' => [
                    'email' => $email,
                    'recipientlist_id' => $recipientlistId,
                ],
            ]
        );

        return $this->decodeJson($response);
    }
}
