<?php

namespace App\Modules\Email\Sparkpost;

use App\Core\Email\AbstractEmail;
use Illuminate\Support\Facades\Http;

/**
 * PRC-106 — SparkPost transmissions API.
 */
class Sparkpost extends AbstractEmail
{
    protected string $apiUrl = 'https://api.sparkpost.com/api/v1/transmissions';

    public function sendEmail(array $params)
    {
        $validation = $this->validateEmailParams($params);
        if (! $validation['valid']) {
            return ['success' => false, 'errors' => $validation['errors']];
        }
        $key = $this->getConfig('api_key');
        if (! $key) {
            return ['success' => false, 'error' => 'SparkPost api_key missing'];
        }

        $recipients = is_array($params['to'])
            ? array_map(fn ($e) => ['address' => ['email' => $e]], $params['to'])
            : [['address' => ['email' => $params['to']]]];

        $body = [
            'recipients' => $recipients,
            'content' => [
                'from' => [
                    'email' => $params['from'] ?? $this->getConfig('from_email'),
                    'name' => $params['from_name'] ?? $this->getConfig('from_name', ''),
                ],
                'subject' => $params['subject'],
                'html' => $params['html_content'] ?? $params['content'] ?? '',
                'text' => $params['text_content'] ?? $this->htmlToText($params['html_content'] ?? $params['content'] ?? ''),
            ],
        ];
        if (! empty($params['attachments'])) {
            $body['content']['attachments'] = array_map(fn ($a) => [
                'name' => $a['name'] ?? basename($a['path']),
                'type' => $a['mime'] ?? 'application/octet-stream',
                'data' => base64_encode(file_get_contents($a['path'])),
            ], $params['attachments']);
        }

        try {
            $resp = Http::withHeaders(['Authorization' => $key, 'Content-Type' => 'application/json'])
                ->timeout(30)
                ->post($this->apiUrl, $body);
            if (! $resp->successful()) {
                return ['success' => false, 'error' => 'SparkPost HTTP '.$resp->status()];
            }

            // HTTP 200 olsa da gövde per-mesaj hata/red taşıyabilir; başarıyı
            // gövde-statüsüyle de gate et.
            $errors = $resp->json('errors');
            if (! empty($errors)) {
                return ['success' => false, 'error' => 'SparkPost API error'];
            }

            $accepted = (int) ($resp->json('results.total_accepted_recipients') ?? 0);
            $rejected = (int) ($resp->json('results.total_rejected_recipients') ?? 0);
            $messageId = $resp->json('results.id');
            if ($accepted < 1 || ! $messageId) {
                return ['success' => false, 'error' => 'SparkPost rejected all recipients ('.$rejected.' rejected)'];
            }

            return [
                'success' => true,
                'message_id' => $messageId,
                'message' => 'Sent via SparkPost',
            ];
        } catch (\Throwable $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    public function renderTemplate(array $params)
    {
        return ['success' => true, 'rendered' => $params['content'] ?? ''];
    }

    public function testConnection(array $params)
    {
        $key = $params['api_key'] ?? $this->getConfig('api_key');
        if (! $key) {
            return ['success' => false, 'message' => 'api_key required'];
        }
        $resp = Http::withHeaders(['Authorization' => $key])->timeout(15)
            ->get('https://api.sparkpost.com/api/v1/account');

        return $resp->successful()
            ? ['success' => true, 'message' => 'SparkPost connection OK']
            : ['success' => false, 'message' => 'SparkPost HTTP '.$resp->status()];
    }

    protected function getRequiredConfigFields(): array
    {
        return ['api_key', 'from_email', 'from_name'];
    }

    /**
     * Email pipeline config anahtarlarını YALNIZ buradan okur
     * (EmailManager::getProviderConfig → ModuleConfig::resolved). adminFields()
     * Email ailesinde ölü olduğundan gerçek alanlar burada tanımlanır.
     * SparkPost tek api_key ile çalışır (Authorization: <api_key>); api_secret yok.
     */
    public function getConfigFields(): array
    {
        return [
            'api_key' => [
                'type' => 'password',
                'label' => 'SparkPost API Key',
                'required' => true,
                'encrypted' => true,
                'description' => 'SparkPost API anahtarı (Authorization header)',
            ],
            'from_email' => [
                'type' => 'email',
                'label' => __('modules.email_config_from_email'),
                'required' => true,
                'description' => __('modules.email_config_from_email_desc'),
            ],
            'from_name' => [
                'type' => 'text',
                'label' => __('modules.email_config_from_name'),
                'required' => true,
                'description' => __('modules.email_config_from_name_desc'),
            ],
        ];
    }
}
