<?php

namespace App\Services;

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

class MailService
{
    public function sendTemplate($to, string $subject, string $view, array $data = [], bool $queue = false): void
    {
        $toList = is_array($to) ? $to : [$to];

        // ✅ 웹 요청 기준으로 실제 mail 설정을 로그로 남김
        Log::info('mail_send_debug', [
            'queue' => $queue,
            'queue_default' => config('queue.default'),
            'mail_default' => config('mail.default'),
            'smtp' => [
                'host' => config('mail.mailers.smtp.host'),
                'port' => config('mail.mailers.smtp.port'),
                'encryption' => config('mail.mailers.smtp.encryption'),
                'timeout' => config('mail.mailers.smtp.timeout'),
                'local_domain' => config('mail.mailers.smtp.local_domain'),
            ],
            'from' => config('mail.from'),
        ]);

        foreach ($toList as $toEmail) {
            $mailable = new TemplateMail(
                subjectText: $subject,
                viewName: $view,
                payload: $data
            );

            Log::info('mail_send_attempt', [
                'to' => $toEmail,
                'subject' => $subject,
                'view' => $view,
            ]);

            if ($queue) {
                Mail::to($toEmail)->queue($mailable);
                Log::info('mail_send_queued', ['to' => $toEmail]);
            } else {
                Mail::to($toEmail)->send($mailable);
                Log::info('mail_send_done', ['to' => $toEmail]);
            }
        }
    }
}
