const Component = require(`vn-print/core/component`);
const emailBody = new Component('email-body');
const attachment = new Component('attachment');
const db = require('../../../core/database');

module.exports = {
    name: 'letter-debtor-nd',
    async serverPrefetch() {
        this.debtor = await db.findOne(`
        SELECT sa.id,
            sa.iban,
            be.name bankName,
            sa.countryFk,
            c.countryFk
        FROM supplierAccount sa
            JOIN bankEntity be ON sa.bankEntityFk = be.id
            LEFT JOIN company co ON co.supplierAccountFk = sa.id
            JOIN client c ON c.countryFk = sa.countryFk
        WHERE c.id = ?;
        `, [this.id]);
        if (!this.debtor) {
            this.debtor = await db.findOne(`
                SELECT sa.iban,
                    be.name bankName
                FROM supplierAccount sa
                    JOIN bankEntity be ON sa.bankEntityFk = be.id
                    JOIN company co ON co.supplierAccountFk = sa.id
                WHERE co.id = ?;
        `, [this.companyId]);
        }
    },
    data() {
        return {
            attachments: [
                {
                    filename: 'letter-debtor.pdf',
                    type: 'pdf',
                    path: `Clients/${this.id}/letter-debtor-pdf`
                }
            ]
        };
    },
    methods: {
        fetchDebtor(id, companyId) {
            return this.findOneFromDef('client', [id, companyId]);
        }
    },
    components: {
        'email-body': emailBody.build(),
        'attachment': attachment.build()
    },
    props: {
        id: {
            type: Number,
            required: true
        },
        companyId: {
            type: Number,
            required: true
        }
    }
};