const database = require(`${appPath}/lib/database`);
const emailHeader = require('../email-header');
const emailFooter = require('../email-footer');
const UserException = require(`${appPath}/lib/exceptions/userException`);

module.exports = {
    name: 'payment-update',
    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() {
        this.$i18n.locale = this.locale;
    },
    methods: {
        fetchClient(clientFk) {
            return database.pool.query(`
            SELECT
                u.lang locale,
                c.email recipient,
                c.dueDay,
                c.iban,
                pm.id payMethodFk,
                pm.name payMethodName
            FROM client c
                JOIN payMethod pm ON pm.id = c.payMethodFk
                JOIN account.user u ON u.id = c.id
            WHERE c.id = ?`, [clientFk]);
        },
    },
    computed: {
        accountAddress: function() {
            return this.iban.slice(-4);
        },
    },
    components: {
        'email-header': emailHeader,
        'email-footer': emailFooter,
    },
};