<?php

namespace App\Jobs;

use App\Services\MailService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SendUserQnaAnsweredMailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 30;

    public function __construct(
        public string $toEmail,
        public int $memNo,
        public int $qnaId,
        public array $data = []
    ) {}

    public function handle(MailService $mail): void
    {
        $to = trim($this->toEmail);
        if ($to === '') return;

        try {
            $mail->sendTemplate(
                $to,
                '[PIN FOR YOU] 1:1 문의 답변 안내',
                'mail.admin.qna_adminreturn',
                [
                    'mem_no' => $this->memNo,
                    'qna_id' => $this->qnaId,
                    'year' => $this->data['year'] ?? null,
                    'enquiry_code' => $this->data['enquiry_code'] ?? '',
                    'enquiry_title' => $this->data['enquiry_title'] ?? '',
                    'enquiry_content' => $this->data['enquiry_content'] ?? '',
                    'answer_content' => $this->data['answer_content'] ?? '',
                    'answer_sms' => $this->data['answer_sms'] ?? '',
                    'regdate' => $this->data['regdate'] ?? '',
                    'completed_at' => $this->data['completed_at'] ?? now()->toDateTimeString(),
                    'siteUrl' => config('app.url'),
                    // 'qnaUrl' => ... (원하면 상세 링크)
                ],
                queue: false
            );
        } catch (\Throwable $e) {
            Log::error('[QNA] user answered mail failed', [
                'mem_no' => $this->memNo,
                'qna_id' => $this->qnaId,
                'email' => $to,
                'err' => $e->getMessage(),
            ]);
        }
    }
}
