<?php

namespace Tricks\CampaignMonitor\Http\Controllers;

use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Tricks\CampaignMonitor\CampaignMonitorFacade;
use Tricks\CampaignMonitor\Http\Requests\CampaignMonitorRequest;
use Tricks\CampaignMonitor\Helpers\Exceptional;

class CampaignMonitorController
{
    /**
     * @param CampaignMonitorRequest $request
     * @return JsonResponse
     */
    public function sendTransactional(CampaignMonitorRequest $request): JsonResponse
    {
        $formType = Str::afterLast($request->route()->getName(), '.');

        try {
            $smartEmailId = Exceptional::config('campaignmonitor.transactional.mails.' . $formType . '.id');

            $smartEmailRecipient = config('campaignmonitor.transactional.mails.' . $formType . '.recipient');

            $validated = $request->validated();

            $recipient = $smartEmailRecipient ?? $this->getRecipientByAttribute($validated);

            $attachments = Arr::pull($validated, 'attachments');

            if (empty($attachments)) {
                $attachments = [];
            }

            $result = CampaignMonitorFacade::sendTransactional($smartEmailId, $recipient, $validated, $attachments);
        } catch (Exception $exception) {
            return $this->responseError([
                'laravel_error' => $exception->getMessage()
            ]);
        }

        if (!$result->was_successful()) {
            return $this->responseError([
                'campaignmonitor_error' => $result->response
            ], $result->http_status_code);
        }

        return response()->json([
            'response' => $result->response
        ]);
    }

    private function responseError($error, $statusCode = 500)
    {
        return response()->json($error, $statusCode);
    }

    /**
     * @throws Exception
     */
    private function getRecipientByAttribute($validated)
    {
        $recipientFromRequest = $validated['recipient'] ?? null;

        if (!$recipientFromRequest) {
            throw new Exception('The recipient is missing.');
        }

        return $recipientFromRequest;
    }
}
