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

class PasswordResetJob 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(`Resetting password for user: ${user.uid}`)

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

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

            await this.jobs.queue('mailer').add('EMail', {
                to: user.email,
                subject: 'Reset Your Password | ' + this.configs.get('app.name'),
                email_params: {
                    header_text: 'Forget your password?',
                    body_paragraphs: [
                        'It looks like you requested a password reset for your account. Click the button below, and we\'ll walk you through creating a new one.',
                        'If you didn\'t request this e-mail, please contact your system administrator.',
                    ],
                    button_text: 'Reset Password',
                    button_link: key_action.url(),
                }
            })

            this.info('Logged e-mail job.')

            if ( user.notify_config && user.notify_config.active ) {
                await user.notify_config.log({
                    title: `${this.configs.get('app.name')}: Password Reset Requested`,
                    message: `A password reset request was logged for your account (${user.uid}). If this was you, please check your e-mail for further instructions.`,
                    priority: 8,
                })

                this.info('Logged security push notification job')
            }

            this.success('Password reset logged.')
        } catch (e) {
            this.error(e)
            throw e
        }
    }

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

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

module.exports = exports = PasswordResetJob
