<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class SendGridEmailService {

    private string $apiKey;
    private string $baseUrl = 'https://api.sendgrid.com/v3';

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

    public function send(array $message): array {
        $payload = [
            'personalizations' => [
                [
                    'to' => [
                        [
                            'email' => $message['to_email'],
                            'name'  => $message['to_name'] ?? '',
                        ],
                    ],
                ],
            ],
            'from' => [
                'email' => $message['from_email'],
                'name'  => $message['from_name'] ?? '',
            ],
            'subject' => $message['subject'] ?? '',
        ];

        // Body content — only included when not using a template
        if (empty($message['template_id'])) {
            $content = [];
            if (!empty($message['text'])) {
                $content[] = ['type' => 'text/plain', 'value' => $message['text']];
            }
            if (!empty($message['html'])) {
                $content[] = ['type' => 'text/html', 'value' => $message['html']];
            }
            if (!empty($content)) {
                $payload['content'] = $content;
            }
        }

        if (!empty($message['reply_to'])) {
            $payload['reply_to'] = ['email' => $message['reply_to']];
        }

        if (!empty($message['attachments'])) {
            $payload['attachments'] = collect($message['attachments'])
                ->map(fn($a) => [
                    'content'  => $a['content'],
                    'type'     => $a['mime'],
                    'filename' => $a['name'],
                ])
                ->all();
        }

        if (!empty($message['template_id'])) {
            $payload['template_id'] = $message['template_id'];
            $payload['personalizations'][0]['dynamic_template_data'] = $message['template_data'] ?? [];
        }

        $response = Http::withToken($this->apiKey)
            // Skip TLS verification only in local dev to work around missing
            // Windows CA bundles.  Production keeps strict verification.
            ->withOptions(['verify' => !app()->environment('local')])
            ->post($this->baseUrl . '/mail/send', $payload);

        $response->throw();

        // SendGrid returns 202 Accepted with no body; message ID is in the response header
        return [
            'status'  => $response->status(),
            'body'    => $response->json() ?? [],
            'headers' => $response->headers(),
        ];
    }
}
