<?php

namespace App\Services\BroadcastEmail;

use App\Services\EmailService;

class BroadcastEmailDispatchService
{
    private EmailService $mailer;
    private BroadcastEmailComposerService $composer;

    public function __construct(EmailService $mailer, BroadcastEmailComposerService $composer)
    {
        $this->mailer = $mailer;
        $this->composer = $composer;
    }

    public function sendTest(array $payload): array
    {
        $html = $this->composer->compose(
            (bool) $payload['wrap_layout'],
            $payload['subject'],
            $payload['body_html'],
            $payload['recipient_name'],
            $payload['preheader'],
            $payload['cta_text'],
            $payload['cta_url'],
            (bool) $payload['personalize']
        );

        $ok = $this->mailer->send(
            $payload['test_email'],
            '[TEST] ' . $payload['subject'],
            $html,
            $payload['from_key']
        );

        return [
            'ok' => $ok,
            'message' => $ok
                ? "Test email sent to {$payload['test_email']}."
                : 'Test email failed (mailer->send() returned false). Check logs.',
        ];
    }

    public function sendBroadcast(array $payload, array $recipients): array
    {
        $stats = [
            'attempted' => 0,
            'sent' => 0,
            'failed' => 0,
            'mode' => $payload['mode'],
        ];

        foreach ($recipients as $recipient) {
            $stats['attempted']++;
            $recipientName = $recipient['name'] ?: 'Parent';
            $html = $this->composer->compose(
                (bool) $payload['wrap_layout'],
                $payload['subject'],
                $payload['body_html'],
                $recipientName,
                $payload['preheader'],
                $payload['cta_text'],
                $payload['cta_url'],
                (bool) $payload['personalize']
            );

            $ok = $this->mailer->send(
                (string) $recipient['email'],
                $payload['subject'],
                $html,
                $payload['from_key']
            );

            $ok ? $stats['sent']++ : $stats['failed']++;
        }

        return $stats;
    }
}
