const { Job } = require('flitter-jobs')

class SendVerificationEmailJob extends Job {
    static get services() {
        return [...super.services, 'models', 'jobs', 'output', 'configs']
    }

    async execute(job) {
        const {data} = job
        const {user_id} = data

        try {
            const User = this.models.get('auth:User')
            const user = await User.findById(user_id)
            if (!user) {
                this.error(`Unable to find user with ID: ${user_id}`)
                throw new Error('Unable to find user with that ID.')
            }

            this.info(`Sending verification email for user: ${user.uid}`)

            // Create an authenticated key-action
            const key_action = await this.key_action(user)

            this.info(`Created verification keyaction ${key_action.id} (key: ${key_action.key}, handler: ${key_action.handler})`)

            await this.jobs.queue('mailer').add('EMail', {
                to: user.email,
                subject: 'Confirm Your E-mail | ' + this.configs.get('app.name'),
                email_params: {
                    header_text: 'Confirm Your E-mail',
                    body_paragraphs: [
                        'The e-mail address for your ' + this.configs.get('app.name') + ' was set or changed. Click the link below to verify this change.',
                        'If you didn\'t request this e-mail, please contact your system administrator.',
                    ],
                    button_text: 'Confirm E-mail',
                    button_link: key_action.url(),
                }
            })

            this.info('Logged e-mail job.')
        } catch (e) {
            this.error(e)
            throw e
        }
    }

    async key_action(user) {
        const KeyAction = this.models.get('auth:KeyAction')
        const ka_data = {
            handler: 'controller::auth:Forms.email_verify_keyaction',
            used: false,
            user_id: user._id,
            auto_login: true,
            no_auto_logout: false,
        }

        return (new KeyAction(ka_data)).save()
    }
}

module.exports = exports = SendVerificationEmailJob
