const { frontendBase, jwtSecret, logoPath, noReplyEmail, operatorEmail, serverBaseURL } = require("../config")
const { getCustomerById } = require("../lib/bigcommerceRestAPI")
const { createNewsletterSubscriber, checkIfNewsletterSubscriber } = require("../lib/omnisendRestApi")
const { cryptchaCheck } = require("../lib/utils")
;(function () {
    const operation = context.data.operation
    if (operation === "requestPasswordReset") {
        cryptchaCheck()
        requestPasswordReset()
    } else if (operation === "checkUsernameTaken") {
        const username = context.data.username
        const user = context.db.find("bigCommerceCustomer", {
            filter: { username: username.toLowerCase() },
        })[0]

        throw {
            status: 200,
            data: !!user,
        }
    } else if (operation === "reportRecord") {
        const customerId = context.data.customerId
        if (!customerId) {
            throw {
                status: 400,
                message: "customerId is required",
            }
        }
        const recordTitle = context.data.record

        context.smtp.sendMail({
            to: operatorEmail,
            from: noReplyEmail,
            fromName: "BinKrassDuFass",
            replyTo: noReplyEmail,
            subject: "Record Reported",
            plain: "Record reported, customer ID: " + customerId + ", record: " + recordTitle,
        })
        throw {
            status: 200,
            message: "Record reported",
        }
    } else if (operation === "subscribeToNewsletter") {
        if (!context.data.email) {
            throw {
                status: 400,
                message: "Email is required",
            }
        }
        createNewsletterSubscriber(context.data.email?.toLowerCase())
        throw {
            status: 200,
            message: "Newsletter subscriber created",
        }
    } else if (operation === "checkIfNewsletterSubscriber") {
        const email = context.data.email
        const isSubscriber = checkIfNewsletterSubscriber(email.toLowerCase())
        throw {
            status: 200,
            data: isSubscriber,
        }
    }
})()

/**
 *
 * @param {string} tibiId
 * @param {string} bigCommerceId
 * @param {string} key
 * @returns {string}
 */
function buildPwResetToken(tibiId, bigCommerceId, key) {
    return context.jwt.create(
        {
            tibiId: tibiId,
            bigCommerceId: bigCommerceId,
            check: key,
        },
        {
            secret: jwtSecret,
            validityDuration: 60 * 60 * 24 * 90, // 90 days
        }
    )
}

function requestPasswordReset() {
    const random256BitString = Math.random().toString(36).substring(2, 34)
    const email = context.data.email
    if (!email) {
        throw {
            status: 400,
            message: "Email is required",
        }
    }
    let customer = context.db.find("bigCommerceCustomer", {
        filter: { email: email?.toLowerCase() },
    })[0]
    if (!customer) {
        const customerBigCommerce = getCustomerById(null, email)
        if (!customerBigCommerce) {
            throw {
                status: 404,
                message: "Customer not found",
            }
        }
        const username = customerBigCommerce.form_fields.find((field) => field.name === "username")?.value
        customer = context.db.create("bigCommerceCustomer", {
            bigCommerceId: customerBigCommerce.id,
            email: customerBigCommerce.email.toLowerCase(),
            username: username ? username?.toLowerCase() : Math.random().toString(36).substring(2, 15),
        })
    }

    const pwResetToken = buildPwResetToken(customer.id, customer.bigCommerceId, random256BitString)
    const store = {
        logo: `${serverBaseURL}${logoPath}`,
        frontendBase,
        pwReset: `${frontendBase}profile/reset-password?token=${pwResetToken}`,
    }
    const html = context.tpl.execute(context.fs.readFile("templates/requestPWReset.html"), {
        store,
    })

    context.smtp.sendMail({
        to: email,
        from: operatorEmail,
        fromName: "BinKrassDuFass",
        replyTo: noReplyEmail,
        subject: "Passwort Zurücksetzen",
        html,
    })
    context.db.update("bigCommerceCustomer", customer.id, {
        currentToken: random256BitString,
    })
    throw {
        status: 200,
        message: "Password reset email sent",
    }
}
