const axios = require('axios');

const apiUrl = 'https://api.cloudflare.com/client/v4'; // Endpoint 

class Mailinabox {
    constructor(config) {
        this.config = config ? config : {};
        if (!this.config.miabHost) {
            this.config.miabHost = process.env.MIAB_HOST;
            this.config.adminEmail = process.env.MIAB_ADMIN_EMAIL;
            this.config.adminPassword = process.env.MIAB_ADMIN_PASSWORD;
        }

    }

    init() {
        if (this.config.arrTokens) {
            this.zones = [];
        }
    }

    checkIfParamOk() {
        if (!this.config.miabHost || !this.config.adminEmail || !this.config.adminPassword) {
            console.error('Configurazione mancante per il recupero del record DKIM.');
            return false;
        }

        return true;
    }


    // Funzione per ottenere il record DKIM
    async getDKIMRecord(domain) {

        if (!this.checkIfParamOk()) {
            return '';
        }

        const url = `https://${this.config.miabHost}/admin/dns/zonefile/${domain}`;
        const auth = Buffer.from(`${this.config.adminEmail}:${this.config.adminPassword}`).toString('base64');

        try {
            const response = await axios.get(url, {
                headers: {
                    'Authorization': `Basic ${auth}`
                }
            });

            // console.log(`Record DNS esterni per ${config.domain}:`);

            // Analizza la risposta per estrarre i record DNS
            const records = response.data.split('\n')
                .filter(line => line.trim() !== '' && !line.startsWith(';'))
                .map(line => line.trim());

            // Trova e stampa il record DKIM
            const dkimRecord = records.find(record => record.includes('mail._domainkey'));
            if (dkimRecord) {

                const pattern = /p=([A-Za-z0-9+/=]+)(?:"\s*"([A-Za-z0-9+/=]+))?/;

                // Esegui la ricerca
                const match = dkimRecord.match(pattern);

                if (match) {
                    // Concatena le due parti trovate di 'p', la seconda parte è facoltativa
                    return match[1] + (match[2] || '');
                } else {
                    console.log('Record DKIM non trovato.');
                }
            }

            return '';

        } catch (error) {
            console.error('Errore nel recupero del record DKIM:', error.message);
            if (error.response) {
                console.error('Dettagli errore:', error.response.data);
            }
        }

        return '';
    }

    async MIAB_getEmails(myrec) {

        if (!this.checkIfParamOk() || !myrec.domain) {
            return;
        }

        const url = `https://${this.config.miabHost}/admin/mail/users?format=text`;
        const auth = Buffer.from(`${this.config.adminEmail}:${this.config.adminPassword}`).toString('base64');

        try {
            const response = await axios.get(url, {
                headers: {
                    'Authorization': `Basic ${auth}`
                }
            });

            const records = response.data.split('\n')
                .filter(line => line.trim() !== '' && line.indexOf(myrec.domain) > -1)
                .map(line => line.trim());

            return records;

        } catch (error) {
            console.error('Errore nel recupero delle Email ', error.message);
            if (error.response) {
                console.error('Dettagli errore:', error.response.data);
            }
        }

        return '';
    }
    async removeEmail(myrec) {

        if (!this.checkIfParamOk() || !myrec.email) {
            return;
        }

        const url = `https://${this.config.miabHost}/admin/mail/users/remove`;
        const auth = Buffer.from(`${this.config.adminEmail}:${this.config.adminPassword}`).toString('base64');

        try {
            const myrecout = `email=${myrec.email}`;

            const response = await axios.post(url, myrecout, {
                headers: {
                    'Authorization': `Basic ${auth}`
                }
            });

            const ris = response.data;

            return ris;

        } catch (error) {
            console.error('Errore nella cancellazione della Email ' + record.email, error.message);
            if (error.response) {
                console.error('Dettagli errore:', error.response.data);
            }
        }

        return '';
    }
    async addEmail(myrec) {

        if (!this.checkIfParamOk() || !myrec.email) {
            return;
        }

        const url = `https://${this.config.miabHost}/admin/mail/users/add`;
        const auth = Buffer.from(`${this.config.adminEmail}:${this.config.adminPassword}`).toString('base64');

        try {
            let privileges = myrec.privileges ? 'admin' : ''
            const myrecout = `email=${myrec.email}&password=${myrec.pwd}&privileges="${privileges}"`;

            const response = await axios.post(url, myrecout, {
                headers: {
                    'Authorization': `Basic ${auth}`
                }
            });

            const ris = response.data;

            return ris;

        } catch (error) {
            console.error('Errore nella creazione della Email ' + record.email, error.message);
            if (error.response) {
                console.error('Dettagli errore:', error.response.data);
            }
        }

        return '';
    }
    async setMailUserPassword(myrec) {

        if (!this.checkIfParamOk() || !myrec.email) {
            return;
        }

        const url = `https://${this.config.miabHost}/admin/mail/users/password`;
        const auth = Buffer.from(`${this.config.adminEmail}:${this.config.adminPassword}`).toString('base64');

        try {

            let data = `email=${myrec.email}&password=${myrec.pwd}`;

            const response = await axios.post(url,
                data,
                {
                    headers: {
                        'Authorization': `Basic ${auth}`,
                        'Content-Type': 'application/x-www-form-urlencoded',
                    }
                });

            let ris = '';

            if (response.status === 200) {
                ris = `Password cambiata con successo per ${myrec.email}`;
            } else {
                ris = `Errore nel cambio password per ${myrec.email}`;
            }

            return ris;

        } catch (error) {
            console.error('Errore nella creazione della Email ' + record.email, error.message);
            if (error.response) {
                console.error('Dettagli errore:', error.response.data);
            }
        }

        return '';
    }
}

module.exports = Mailinabox