const database = require(`${appPath}/lib/database`);
const UserException = require(`${appPath}/lib/exceptions/userException`);

module.exports = {
    name: 'client-welcome',
    async asyncData(ctx, params) {
        const data = {
            isPreview: ctx.method === 'GET',
        };

        if (!params.clientFk)
            throw new UserException('No client id specified');

        return this.methods.fetchClient(params.clientFk)
            .then(([result]) => {
                if (!result)
                    throw new UserException('No client data found');
                return Object.assign(data, result[0]);
            });
    },
    created() {
        if (this.locale)
            this.$i18n.locale = this.locale;
    },
    methods: {
        fetchClient(clientFk) {
            return database.pool.query(`
                SELECT
                    c.id,
                    u.lang locale,
                    u.name AS userName,
                    c.email recipient,
                    CONCAT(w.name, ' ', w.firstName) salesPersonName,
                    w.phone AS salesPersonPhone,
                    CONCAT(wu.name, '@verdnatura.es') AS salesPersonEmail
                FROM client c
                    JOIN account.user u ON u.id = c.id
                    LEFT JOIN worker w ON w.id = c.salesPersonFk
                    LEFT JOIN account.user wu ON wu.id = w.userFk
                WHERE c.id = ?`, [clientFk]);
        },
    },
    components: {
        'email-header': require('../email-header'),
        'email-footer': require('../email-footer'),
    },
};