<?php

namespace App\Newsletter;

use App\Contracts\NewsletterProvider;
use CS_REST_Subscribers;
use Exception;

class CampaignMonitor implements NewsletterProvider
{
    /**
     * CampaignMonitor constructor.
     * Initializes the connection with CampaignMonitor API
     *
     * @param CS_REST_Subscribers $api
     */
    public function __construct(private readonly CS_REST_Subscribers $api)
    {
    }

    /**
     * Sign up method
     *
     * @param string $email email address to sign up
     * @param array $additional_params any additional params passed to interface
     * @return bool
     */
    public function signUp(string $email, array $additional_params = []): bool
    {
        $result = $this->api->add([
            'EmailAddress' => $email,
            'Name' => ($additional_params['first_name'] ?? '') . ' ' . ($additional_params['last_name'] ?? ''),
            'Resubscribe' => true
        ]);

        if ($result->was_successful()) {
            return true;
        }
        throw new Exception($result->response->Message);
    }

    /**
     * Check if email already exists in the list
     *
     * @param string $email
     * @return bool
     */
    public function checkIfExists(string $email): bool
    {
        return $this->api->get($email)->was_successful();
    }
}
