<?php

namespace App\Infrastructure\Api\RapidMail;

use App\Framework\Http\Method;
use App\Infrastructure\Api\RapidMail\ReadModels\RecipientList;

final readonly class RecipientListService
{
    public function __construct(
        private RapidMailApiClient $apiClient
    ) {}

    /**
     * Erstellt eine neue Empfängerliste
     */
    public function create(string $name, ?string $description = null): RecipientList
    {
        $data = ['name' => $name];
        if ($description !== null) {
            $data['description'] = $description;
        }

        $result = $this->apiClient->request(Method::POST, 'recipientlists', $data);
        return RecipientList::fromArray($result);
    }

    /**
     * Holt alle Empfängerlisten
     * @return RecipientList[]
     */
    public function getAll(int $page = 1, int $perPage = 50): array
    {
        $apiResponse = $this->apiClient->request(Method::GET, 'recipientlists', [], [
            'page' => $page,
            'per_page' => $perPage
        ]);

        $recipientlists = $apiResponse['_embedded']['recipientlists'] ?? [];

        return array_map(
            fn(array $item) => RecipientList::fromArray($item),
            $recipientlists
        );
    }

    /**
     * Holt eine spezifische Empfängerliste
     */
    public function get(RecipientListId $recipientlistId): RecipientList
    {
        $data = $this->apiClient->request(Method::GET, "recipientlists/{$recipientlistId->value}");
        return RecipientList::fromArray($data);
    }

    /**
     * Aktualisiert eine Empfängerliste
     */
    public function update(RecipientListId $recipientlistId, string $name, ?string $description = null): RecipientList
    {
        $data = ['name' => $name];
        if ($description !== null) {
            $data['description'] = $description;
        }

        $result = $this->apiClient->request(Method::PUT, "recipientlists/{$recipientlistId->value}", $data);
        return RecipientList::fromArray($result);
    }

    /**
     * Löscht eine Empfängerliste
     */
    public function delete(RecipientListId $recipientlistId): void
    {
        $this->apiClient->sendRawRequest(Method::DELETE, "recipientlists/{$recipientlistId->value}");
    }
}
