<?php

namespace App\Services\EmailCampaign\Drivers;

use App\Models\EmailCampaign;
use App\Models\EmailCampaignRecipient;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class LocalDriver extends AbstractEmailCampaignDriver
{
    public function send(EmailCampaign $campaign, EmailCampaignRecipient $recipient): array
    {
        $body = $this->compileBody($campaign, $recipient);
        if ($body === '') {
            return ['success' => false, 'error' => 'Campaign body is empty'];
        }
        return $this->dispatchMail(
            (string) $recipient->email_snapshot,
            (string) ($campaign->subject ?: $campaign->name),
            $body,
            $campaign,
        );
    }

    public function sendTest(EmailCampaign $campaign, string $email): array
    {
        $body = $this->compileBody($campaign, null);
        if ($body === '') {
            return ['success' => false, 'error' => 'Campaign body is empty'];
        }
        $subject = '[TEST] '.($campaign->subject ?: $campaign->name);
        return $this->dispatchMail($email, $subject, $body, $campaign);
    }

    public function supportsTracking(): bool
    {
        return false;
    }

    protected function dispatchMail(string $to, string $subject, string $html, EmailCampaign $campaign): array
    {
        try {
            Mail::html($html, function ($message) use ($to, $subject, $campaign) {
                $message->to($to)->subject($subject);
                if ($campaign->from_email) {
                    $message->from($campaign->from_email, $campaign->from_name ?: $campaign->from_email);
                }
                if ($campaign->reply_to) {
                    $message->replyTo($campaign->reply_to);
                }
            });
            return ['success' => true];
        } catch (\Throwable $e) {
            Log::warning('LocalDriver send failed', [
                'campaign_id' => $campaign->id,
                'to' => $to,
                'error' => $e->getMessage(),
            ]);
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}
