<?php

namespace App\Services;

use App\Models\ContactMessageReply;
use Illuminate\Support\Facades\Mail;
use Throwable;

class OutboundMailService
{
    public function sendReply(ContactMessageReply $reply): ContactMessageReply
    {
        $settings = app(SiteContentService::class)->email();
        $fromAddress = $settings['sender_address'] ?? config('mail.from.address');
        $fromName = $settings['sender_name'] ?? config('mail.from.name');
        $replyTo = $settings['reply_to'] ?? $fromAddress;

        $reply->forceFill(['status' => 'sending', 'failure_message' => null])->save();

        try {
            Mail::html($this->body($reply), function ($message) use ($reply, $fromAddress, $fromName, $replyTo): void {
                $message->to($reply->to_email)
                    ->subject($reply->subject)
                    ->from($fromAddress, $fromName)
                    ->replyTo($replyTo ?: $fromAddress);

                if ($reply->cc_email) {
                    $message->cc($reply->cc_email);
                }
            });

            $reply->forceFill([
                'status' => 'sent',
                'sent_at' => now(),
                'failure_message' => null,
            ])->save();

            return $reply;
        } catch (Throwable $exception) {
            $reply->forceFill([
                'status' => 'failed',
                'failure_message' => $exception->getMessage(),
            ])->save();

            throw $exception;
        }
    }

    private function body(ContactMessageReply $reply): string
    {
        $body = $reply->body;

        if ($reply->signature) {
            $body .= '<br><br>'.nl2br(e($reply->signature));
        }

        return $body;
    }
}
