// @ts-check
let utils = require("../lib/utils")
const config = require("../config")

const { operatorEmail } = config
// const { objectToText } = require("../lib/helper")

;(function () {
    /** @type {import("tibi-types").HookResponse} */
    let hookResponse

    const type = context.request().query("type")
    if (!type) {
        throw {
            status: 403,
            error: "invalid data",
        }
    }
    if (typeof context.data != "object") {
        throw {
            status: 400,
            error: "invalid body data",
        }
    }

    let to = ""
    let from = ""
    let fromName = ""
    let replyTo = ""
    let subject
    let plainText
    let html

    if (utils.isPublicToken(context)) {
        to = operatorEmail
        from = context.data.email
        fromName = context.data.name
        replyTo = context.data.email

        if (type === "contactForm") {
            subject = utils.tpl(context, "templates/operator_contact_form_subject.de.txt")
            html = utils.tpl(context, "templates/operator_contact_form_body.de.html")
        }
    }

    if ((!plainText && !html) || !subject) {
        throw {
            status: 403,
            error: "invalid mail data",
        }
    }

    context.smtp.sendMail({
        to,
        from,
        fromName,
        subject,
        html,
        // attach: ["attachments/AGB.pdf"],
    })

    throw {
        status: 200,
        message: "ok",
    }

    return hookResponse
})()
