/**
 * Email Service - Handles membership application email notifications
 * Clean Code: Single Responsibility Principle
 */

import nodemailer from 'nodemailer'
import fs from 'fs/promises'
import path from 'path'

/**
 * Gets the correct data path for config files
 * @param {string} filename - Config filename
 * @returns {string} Full path to config file
 */
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
// filename is always a hardcoded constant (e.g., 'config.json'), never user input
function getDataPath(filename) {
  const isProduction = process.env.NODE_ENV === 'production'
  
  if (isProduction) {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    return path.join(process.cwd(), '..', 'server', 'data', filename)
  } else {
    // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
    return path.join(process.cwd(), 'server', 'data', filename)
  }
}

/**
 * Loads configuration from config.json
 * @returns {Promise<Object>} Configuration object
 */
async function loadConfig() {
  try {
    const configPath = getDataPath('config.json')
    const configData = await fs.readFile(configPath, 'utf8')
    return JSON.parse(configData)
  } catch (error) {
    console.error('Could not load config.json:', error.message)
    return {}
  }
}

/**
 * Gets email recipients based on membership type and environment
 * @param {Object} data - Form data
 * @param {Object} config - Configuration
 * @returns {Array<string>} Email addresses
 */
function getEmailRecipients(data, config) {
  const isProduction = process.env.NODE_ENV === 'production'
  
  if (!isProduction) {
    return ['tsschulz@tsschulz.de']
  }
  
  const recipients = []
  
  // Add 1. Vorsitzender
  if (config.vorsitzender && config.vorsitzender.email) {
    recipients.push(config.vorsitzender.email)
  }
  
  // Add Schriftführer
  if (config.schriftfuehrer && config.schriftfuehrer.email) {
    recipients.push(config.schriftfuehrer.email)
  }
  
  // For minors, also add 1. Trainer
  if (!data.isVolljaehrig && config.trainer && config.trainer.email) {
    recipients.push(config.trainer.email)
  }
  
  // Fallback if no recipients found
  if (recipients.length === 0) {
    recipients.push('tsschulz@tsschulz.de')
  }
  
  return recipients
}

/**
 * Creates email transporter
 * @returns {Object} Nodemailer transporter
 */
function createTransporter() {
  const smtpUser = process.env.SMTP_USER
  const smtpPass = process.env.SMTP_PASS
  
  if (!smtpUser || !smtpPass) {
    throw new Error(
      'SMTP-Credentials fehlen! Bitte setzen Sie SMTP_USER und SMTP_PASS in der .env Datei.\n' +
      `Aktuell: SMTP_USER=${smtpUser ? 'gesetzt' : 'FEHLT'}, SMTP_PASS=${smtpPass ? 'gesetzt' : 'FEHLT'}`
    )
  }
  
  return nodemailer.createTransporter({
    host: process.env.SMTP_HOST || 'localhost',
    port: parseInt(process.env.SMTP_PORT) || 587,
    secure: process.env.SMTP_SECURE === 'true',
    auth: {
      user: smtpUser,
      pass: smtpPass
    }
  })
}

/**
 * Sends membership application email
 * @param {Object} data - Form data
 * @param {string} pdfPath - Path to generated PDF
 * @returns {Promise<Object>} Email result
 */
export async function sendMembershipEmail(data, pdfPath) {
  try {
    const config = await loadConfig()
    const recipients = getEmailRecipients(data, config)
    
    // Create transporter
    const transporter = createTransporter()
    
    // Email content
    const subject = `Neuer Mitgliedschaftsantrag - ${data.vorname} ${data.nachname}`
    const message = `Ein neuer Mitgliedschaftsantrag wurde eingereicht.

Antragsteller: ${data.vorname} ${data.nachname}
Mitgliedschaftsart: ${data.mitgliedschaftsart}
Volljährig: ${data.isVolljaehrig ? 'Ja' : 'Nein'}

Das ausgefüllte Formular ist als Anhang verfügbar.`
    
    // Email options
    const mailOptions = {
      from: process.env.SMTP_FROM || 'noreply@harheimertc.de',
      to: recipients.join(', '),
      subject: subject,
      text: message,
      attachments: [
        {
          filename: path.basename(pdfPath),
          path: pdfPath
        }
      ]
    }
    
    // Send email
    const info = await transporter.sendMail(mailOptions)
    
    return {
      success: true,
      message: message,
      recipients: recipients,
      messageId: info.messageId
    }
    
  } catch (error) {
    console.error('Email sending failed:', error.message)
    return {
      success: false,
      message: `E-Mail-Versand fehlgeschlagen: ${error.message}`,
      error: error.message
    }
  }
}