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

class ForeignIPLoginAlertJob 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 foreign IP login 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: 'Login From New IP',
                    body_paragraphs: [
                        `We've detected a login to your ${this.configs.get('app.name')} account from a new IP address (${ip}).`,
                        'If this was you, no further action is required. If this was not you, please log into your account and reset your password.',
                        'Also, consider enabling multi-factor authentication to protect your account.',
                    ],
                    button_text: 'Account Settings',
                    button_link: `${this.configs.get('app.url')}dash/profile`,
                }
            })

            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')}: Sign-In From New IP`,
                    message: `Someone signed into your account (${user.uid}) from the IP address ${ip}. If this was you, no further action is required.`,
                })

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

module.exports = exports = ForeignIPLoginAlertJob
