'use server'

import nodemailer from 'nodemailer'
import { Attachment } from 'nodemailer/lib/mailer'

/**
 * @description 이메일 파라미터 인터페이스
 * @param {string} from 발신자
 * @param {string | string[]} to 수신자
 * @param {string | string[]} cc 참조
 * @param {string} subject 제목
 * @param {string} content 내용
 * @param {Attachment[]} attachments 첨부파일
 */
interface EmailParams {
  from: string
  to: string | string[]
  cc?: string | string[]
  subject: string
  content: string
  attachments?: Attachment[]
  surveyPdf?: {
    id: number
    filename: string
  }
}

export async function sendEmail({ from, to, cc, subject, content, attachments, surveyPdf }: EmailParams): Promise<void> {
  /**
   * @description 조사매물 pdf blob 및 buffer 생성
   */
  let surveyPdfBuffer: Buffer | null = null
  if (surveyPdf) {
    const resp = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/survey-sales/${surveyPdf.id}?isPdf=true`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/pdf',
      },
    })
    if (resp.status == 200) {
      const pdfBlob = await resp.blob()
      surveyPdfBuffer = Buffer.from(await pdfBlob.arrayBuffer())
    }
  }
  const surveyPdfAttachment = surveyPdfBuffer ? [{ filename: '[HANASYS現地調査]' + surveyPdf?.filename + '.pdf', content: surveyPdfBuffer }] : []

  if (!surveyPdfBuffer && surveyPdf) {
    content += `
    <div>
      <p>
        <a
          style="font-size: 13px; font-weight: 400; color: #1259CB; margin-bottom: 5px; text-decoration: underline;"
          href="${process.env.NEXT_PUBLIC_API_URL}/api/survey-sales/${surveyPdf.id}?isPdf=true"
          target="_blank"
        >
          現地調査結果PDFダウンロード
        </a>
      </p>
      <p style="font-size: 13px; font-weight: 400; color: #2e3a59;">
        ※リンクをクリックしてローカル調査結果PDFをダウンロードできます。
      </p>
  </div>
    `
  }
  
  /**
   * @description SMTP 트랜스포터 생성
   */
  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT),
    secure: process.env.SMTP_SECURE === 'true',
    requireTLS: true,
    tls: { rejectUnauthorized: false },
  })

  /**
   * @description 이메일 옵션
   */
  const mailOptions = {
    from,
    to: Array.isArray(to) ? to.join(', ') : to,
    cc: cc ? (Array.isArray(cc) ? cc.join(', ') : cc) : undefined,
    subject,
    html: content,
    attachments: surveyPdf ? surveyPdfAttachment : attachments || [],
  }

  await transporter.sendMail(mailOptions)
}
