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

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

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

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

            this.info('Sending password reset alert to user ' + user.uid)

            await this.jobs.queue('mailer').add('EMail', {
                to: user.email,
                subject: `Security Alert | ${this.configs.get('app.name')}`,
                email_params: {
                    header_text: 'Your Password Was Reset',
                    body_paragraphs: [
                        `The password to your ${this.configs.get('app.name')} account (${user.uid}) was recently reset from the IP ${ip}.`,
                        'If this was you, please disregard this email. Otherwise, please contact your administrator for assistance recovering your account.',
                    ],
                },
            })

            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`,
                    message: `The password to your account (${user.uid}) was reset from the IP address ${ip}. If this was not you, please contact your system administrator.`,
                    priority: 8,
                })

                this.info('Logged push notification job')
            }
        } catch (e) {
            this.error(e)
            throw e
        }
    }
}

module.exports = exports = PasswordResetAlertJob
