<?php

namespace App\Infrastructure\Api\RapidMail;

use App\Framework\Http\Method;

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

    /**
     * Holt alle Mailings
     */
    public function getAll(array $filter = [], int $page = 1, int $perPage = 50): array
    {
        $queryParams = [
            'page' => $page,
            'per_page' => $perPage
        ];

        if (!empty($filter)) {
            $queryParams['filter'] = $filter;
        }

        $data = $this->apiClient->request(Method::GET, 'mailings', [], $queryParams);

        $mailings = $data['_embedded']['mailings'] ?? [];

        return array_map(
                fn(array $item) => Mailing::fromArray($item),
                $mailings
        );
    }

    public function getAllWithPagination(array $filter = [], int $page = 1, int $perPage = 50): array
    {
        $queryParams = [
            'page' => $page,
            'per_page' => $perPage
        ];

        if (!empty($filter)) {
            $queryParams = array_merge($queryParams, $filter);
        }

        $apiResponse = $this->apiClient->request(Method::GET, 'mailings', [], $queryParams);

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

        return [
            'mailings' => array_map(
                fn(array $item) => Mailing::fromArray($item),
                $mailings
            ),
            'page' => $apiResponse['page'] ?? $page,
            'page_count' => $apiResponse['page_count'] ?? 1,
            'total_count' => $apiResponse['total_count'] ?? count($mailings)
        ];
    }

    /**
     * Holt ein spezifisches Mailing
     */
    public function get(int $mailingId): Mailing
    {
        $data = $this->apiClient->request(Method::GET, "mailings/{$mailingId}");
        return Mailing::fromArray($data);
    }

    /**
     * Sendet ein Mailing
     */
    public function send(int $mailingId): array
    {
        return $this->apiClient->request(Method::POST, "mailings/{$mailingId}/send");
    }
}
