<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class MailjetEmailService {

    private string $apiKey;
    private string $apiSecret;
    private string $baseUrl = 'https://api.mailjet.com/v3.1';

    public function __construct() {
        $this->apiKey    = config('services.mailjet.key');
        $this->apiSecret = config('services.mailjet.secret');
    }

    public function send(array $message): array {
        $payload = [
            'Messages' => [
                [
                    'From' => [
                        'Email' => $message['from_email'],
                        'Name'  => $message['from_name'] ?? '',
                    ],
                    'To' => [
                        [
                            'Email' => $message['to_email'],
                            'Name'  => $message['to_name'] ?? '',
                        ],
                    ],
                    'Subject'  => $message['subject'] ?? '',
                    'HTMLPart' => $message['html'] ?? '',
                    'TextPart' => $message['text'] ?? '',
                ],
            ],
        ];

        if (!empty($message['reply_to'])) {
            $payload['Messages'][0]['ReplyTo'] = [
                'Email' => $message['reply_to'],
            ];
        }

        if (!empty($message['attachments'])) {
            $payload['Messages'][0]['Attachments'] = collect($message['attachments'])
                ->map(fn($a) => [
                    'ContentType'   => $a['mime'],
                    'Filename'      => $a['name'],
                    'Base64Content' => $a['content'],
                ])
                ->all();
        }

        if (!empty($message['template_id'])) {
            $payload['Messages'][0]['TemplateID']       = $message['template_id'];
            $payload['Messages'][0]['TemplateLanguage'] = true;
            $payload['Messages'][0]['Variables']        = $message['template_data'] ?? [];
        }

        $response = Http::withBasicAuth($this->apiKey, $this->apiSecret)
            ->post($this->baseUrl . '/send', $payload);

        $response->throw();

        return [
            'status' => $response->status(),
            'body'   => $response->json(),
        ];
    }
}
