<?php

declare(strict_types=1);

final class MailEnvelope
{
    /**
     * @param array<string, string> $headers
     */
    public function __construct(
        public readonly string $to,
        public readonly string $subject,
        public readonly string $htmlBody,
        public readonly string $textBody,
        public readonly string $fromEmail,
        public readonly string $fromName,
        public readonly ?string $replyTo = null,
        public readonly array $headers = [],
    ) {
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'to' => $this->to,
            'subject' => $this->subject,
            'htmlBody' => $this->htmlBody,
            'textBody' => $this->textBody,
            'fromEmail' => $this->fromEmail,
            'fromName' => $this->fromName,
            'replyTo' => $this->replyTo,
            'headers' => $this->headers,
        ];
    }

    /**
     * @param array<string, mixed> $data
     */
    public static function fromArray(array $data): self
    {
        $headers = [];
        foreach (is_array($data['headers'] ?? null) ? $data['headers'] : [] as $name => $value) {
            $name = trim((string) $name);
            if (in_array(strtolower($name), ['x-myron-context', 'x-myron-source'], true)) {
                $headers[$name] = trim((string) $value);
            }
        }

        return new self(
            to: (string) ($data['to'] ?? ''),
            subject: (string) ($data['subject'] ?? ''),
            htmlBody: (string) ($data['htmlBody'] ?? ''),
            textBody: (string) ($data['textBody'] ?? ''),
            fromEmail: (string) ($data['fromEmail'] ?? ''),
            fromName: (string) ($data['fromName'] ?? ''),
            replyTo: isset($data['replyTo']) ? (string) $data['replyTo'] : null,
            headers: $headers,
        );
    }
}
