<?php


use Illuminate\Support\Facades\Config;
use Tricks\CampaignMonitor\CampaignMonitorFacade;
use Tricks\CampaignMonitor\Data\BaseData;
use Tricks\CampaignMonitor\Data\ResultData;


it('can send transactional mail', function () {
    $recipient = 'devops@tricks.de';
    $transaction = 'test';
    $smartEmailId = '123456';

    $spy = $this->spy(CS_REST_Transactional_SmartEmail::class);

    $spy->shouldReceive('set_smartemail_id')
        ->withArgs([$smartEmailId]);

    $spy->shouldReceive('send')
        ->withArgs(
            [
                [
                    "To" => [$recipient],
                    "Data" => ["subject" => "test"]
                ],
                'no'
            ]
        )
        ->andReturn(new CS_REST_Wrapper_Result('Accepted', 200));

    Config::set('campaignmonitor.transactional.mails.'.$transaction, [
        'id' => $smartEmailId
    ]);

    $result = CampaignMonitorFacade::send($transaction, new BaseData(subject: 'test'), $recipient);

    expect($result)
        ->toBeTrue();
});

it('returns cm errors', function () {
    $recipient = 'devops@tricks.de';
    $transaction = 'test';
    $smartEmailId = '123456';

    $spy = $this->spy(CS_REST_Transactional_SmartEmail::class);

    $spy->shouldReceive('set_smartemail_id')
        ->withArgs([$smartEmailId]);

    $spy->shouldReceive('send')
        ->withArgs(
            [
                [
                    "To" => [$recipient],
                    "Data" => ["subject" => "test"]
                ],
                'no'
            ]
        )
        ->andReturn(new CS_REST_Wrapper_Result('Server Error', 500));

    Config::set('campaignmonitor.transactional.mails.'.$transaction, [
        'id' => $smartEmailId
    ]);

    $result = CampaignMonitorFacade::send($transaction, new BaseData(subject: 'test'), $recipient);

    expect($result)
        ->toBeInstanceOf(ResultData::class)
        ->and($result->code)
        ->toBe(500)
        ->and($result->campaign_monitor_error)
        ->toBe('"Server Error"');
});

it('returns laravel exceptions', function () {
    $recipient = 'devops@tricks.de';
    $transaction = 'test';

    $spy = $this->spy(CS_REST_Transactional_SmartEmail::class);

    $spy->shouldNotReceive('set_smartemail_id', 'send');


    $result = CampaignMonitorFacade::send($transaction, new BaseData(subject: 'test'), $recipient);

    expect($result)
        ->toBeInstanceOf(ResultData::class)
        ->and($result->code)
        ->toBe(0)
        ->and($result->laravel_error)
        ->toBe("Missing config value for 'campaignmonitor.transactional.mails.test.id'.");
});