<?php

namespace App\Modules\Email\Ses;

use App\Core\Email\AbstractEmail;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\HtmlString;

/**
 * PRC-106 — Amazon SES wrapper.
 *
 * Uses Laravel's native `ses` mailer transport. Settings are pushed into
 * Config at runtime so the module remains self-contained (no .env edits
 * required by the operator).
 *
 * Settings:
 *   access_key   — AWS access key id
 *   secret_key   — AWS secret access key
 *   region       — AWS region (default: us-east-1)
 */
class Ses extends AbstractEmail
{
    public function sendEmail(array $params)
    {
        $validation = $this->validateEmailParams($params);
        if (! $validation['valid']) {
            return ['success' => false, 'errors' => $validation['errors']];
        }

        $this->configureSes();

        try {
            $sendCallback = function ($message) use ($params) {
                $message->to($params['to'])->subject($params['subject']);
                if (! empty($params['from'])) {
                    $message->from($params['from'], $params['from_name'] ?? '');
                }
                if (! empty($params['cc'])) {
                    $message->cc($params['cc']);
                }
                if (! empty($params['bcc'])) {
                    $message->bcc($params['bcc']);
                }
                if (! empty($params['attachments'])) {
                    foreach ($params['attachments'] as $a) {
                        $message->attach($a['path'], ['as' => $a['name'] ?? '', 'mime' => $a['mime'] ?? '']);
                    }
                }
            };

            $html = $params['html_content'] ?? null;
            $isHtml = $params['is_html'] ?? false;
            $content = $params['content'] ?? '';

            // Efektif HTML gövdesini belirle.
            $effectiveHtml = null;
            if (! empty($html)) {
                $effectiveHtml = $html;
            } elseif ($isHtml && $content !== '') {
                $effectiveHtml = $content;
            }

            if ($effectiveHtml !== null) {
                // PRC-1115 (PRC-1073 follow-up) — düzgün multipart/alternative
                // (text/html + link-koruyan text/plain). SMTP ile aynı sözleşme:
                // Mail::send array formatı ('html' Htmlable, 'raw' text part) →
                // Symfony multipart üretir, view lookup YOK. Önceden ->html() yalnız
                // HTML part gönderiyordu (text part yoktu → deliverability düşük).
                $text = $params['text_content'] ?? $this->htmlToText($effectiveHtml);
                $sent = Mail::mailer('ses')->send(
                    ['html' => new HtmlString($effectiveHtml), 'raw' => $text],
                    [],
                    $sendCallback
                );
            } else {
                $sent = Mail::mailer('ses')->raw($content, $sendCallback);
            }

            // Gerçek SES/Symfony mesaj kimliğini al; yoksa UYDURMA (null bırak).
            $messageId = null;
            if ($sent && method_exists($sent, 'getMessageId')) {
                $messageId = $sent->getMessageId();
            }

            $result = ['success' => true, 'message' => 'Sent via SES'];
            if ($messageId) {
                $result['message_id'] = $messageId;
            }

            return $result;
        } 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['access_key'] ?? $this->getConfig('access_key');
        $secret = $params['secret_key'] ?? $this->getConfig('secret_key');
        if (! $key || ! $secret) {
            return ['success' => false, 'message' => 'access_key/secret_key required'];
        }

        // SES IAM authentication isn't trivial via plain HTTP without aws-sdk;
        // signal "configured" if both fields are present. Real-send via
        // sendEmail() will surface AWS auth errors.
        return ['success' => true, 'message' => 'SES credentials configured (live test on first send)'];
    }

    /**
     * Email pipeline config anahtarlarını YALNIZ buradan okur
     * (EmailManager::getProviderConfig → ModuleConfig::resolved yalnız
     * bildirilen key'leri resolve eder). SES ikili-kimlikli olduğu için
     * gerçek alanlar access_key/secret_key/region — AbstractEmail'in
     * api_key/api_secret default'u SES için yanlış (auth null kalır).
     */
    public function getConfigFields(): array
    {
        return [
            'access_key' => [
                'type' => 'password',
                'label' => 'AWS Access Key ID',
                'required' => true,
                'encrypted' => true,
                'description' => 'AWS access key id',
            ],
            'secret_key' => [
                'type' => 'password',
                'label' => 'AWS Secret Access Key',
                'required' => true,
                'encrypted' => true,
                'description' => 'AWS secret access key',
            ],
            'region' => [
                'type' => 'text',
                'label' => 'AWS Region',
                'required' => false,
                'default' => 'us-east-1',
                'description' => 'AWS SES region (varsayılan: us-east-1)',
            ],
            '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' => false,
                'description' => __('modules.email_config_from_name_desc'),
            ],
        ];
    }

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

    private function configureSes(): void
    {
        Config::set('services.ses.key', $this->getConfig('access_key'));
        Config::set('services.ses.secret', $this->getConfig('secret_key'));
        Config::set('services.ses.region', $this->getConfig('region', 'us-east-1'));
    }
}
