import nodemailer from 'nodemailer'
import { getUserFromToken, hasAnyRole } from '../../../../utils/auth.js'
import { addContactReply, readContactRequests } from '../../../../utils/contact-requests.js'

function createTransporter() {
  const smtpUser = process.env.SMTP_USER
  const smtpPass = process.env.SMTP_PASS || process.env.EMAIL_PASSWORD
  if (!smtpUser || !smtpPass) return null

  return nodemailer.createTransport({
    host: process.env.SMTP_HOST || 'smtp.gmail.com',
    port: Number(process.env.SMTP_PORT || 587),
    secure: process.env.SMTP_SECURE === 'true',
    auth: { user: smtpUser, pass: smtpPass }
  })
}

export default defineEventHandler(async (event) => {
  const token = getCookie(event, 'auth_token')
  const currentUser = token ? await getUserFromToken(token) : null

  if (!currentUser || !hasAnyRole(currentUser, 'admin', 'vorstand', 'trainer')) {
    throw createError({
      statusCode: 403,
      statusMessage: 'Zugriff verweigert'
    })
  }

  const body = await readBody(event)
  const replyMessage = String(body?.message || '').trim()
  if (!replyMessage) {
    throw createError({ statusCode: 400, statusMessage: 'Antworttext fehlt' })
  }

  const requestId = getRouterParam(event, 'id')
  if (!requestId) {
    throw createError({ statusCode: 400, statusMessage: 'Anfrage-ID fehlt' })
  }

  const all = await readContactRequests()
  const target = all.find((r) => r.id === requestId)
  if (!target) {
    throw createError({ statusCode: 404, statusMessage: 'Anfrage nicht gefunden' })
  }

  const transporter = createTransporter()
  if (!transporter) {
    throw createError({
      statusCode: 500,
      statusMessage: 'SMTP ist nicht konfiguriert'
    })
  }

  const originalSubject = target.subject || 'Kontaktanfrage'
  const responseSubject = `Aw: ${originalSubject}`

  await transporter.sendMail({
    from: `"Harheimer TC" <${process.env.SMTP_FROM || process.env.SMTP_USER}>`,
    to: target.email,
    subject: responseSubject,
    text: replyMessage
  })

  const responderEmail = currentUser.email || ''
  const updated = await addContactReply({
    requestId,
    replyText: replyMessage,
    responderEmail
  })

  return {
    success: true,
    request: updated
  }
})
