"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatMoeda = exports.downloadImage = exports.horaParaMinuto = exports.getEmailFooter = exports.formatDateDefault = exports.formatDateCompacted = exports.formatDateTime = exports.concatAdress = exports.getDateTime = exports.generateSignature = exports.validateSignature = exports.createHistoricoActividade = exports.deleteDocs = exports.getDocsURL = exports.createRegex = exports.capitalizeFirstCharacter = exports.getAngolaTime = exports.getDiaDaSemanaInt = exports.gerarSlots = exports.getDiaDaSemanaStrig = exports.filterByWeek = exports.filterByMonth = exports.filterByYear = exports.getMes = void 0;
exports.sortBy = sortBy;
exports.generatePassword = generatePassword;
const aws_1 = require("../services/aws");
const validate_url_1 = __importDefault(require("./validate-url"));
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const crypto_1 = __importDefault(require("crypto"));
const prisma_1 = require("../database/prisma");
const getMes = (mes) => {
    const meses = [
        'Janeiro',
        'Fevereiro',
        'Março',
        'Abril',
        'Maio',
        'Junho',
        'Julho',
        'Agosto',
        'Setembro',
        'Outubro',
        'Novembro',
        'Dezembro',
    ];
    return meses[mes - 1];
};
exports.getMes = getMes;
const filterByYear = (year) => {
    const startDate = new Date(year, 0, 1);
    const endDate = new Date(year, 11, 31);
    return {
        gte: startDate,
        lte: endDate,
    };
};
exports.filterByYear = filterByYear;
const filterByMonth = (year, month) => {
    const startDate = new Date(year, month, 1);
    const endDate = new Date(year, month + 1, 0);
    return {
        gte: startDate,
        lte: endDate,
    };
};
exports.filterByMonth = filterByMonth;
const filterByWeek = (year, week) => {
    const startDate = new Date(year, 0, 1); // 1st day of the year
    startDate.setDate(startDate.getDate() + (week - 1) * 7); // Move to the first day of the target week
    const endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + 6); // Move to the last day of the week
    return {
        gte: startDate,
        lte: endDate,
    };
};
exports.filterByWeek = filterByWeek;
const getDiaDaSemanaStrig = (dia) => {
    const diasDaSemana = [
        'Domingo',
        'Segunda feira',
        'Terça feira',
        'Quarta feira',
        'Quinta feira',
        'Sexta feira',
        'Sábado',
    ];
    return diasDaSemana[dia];
};
exports.getDiaDaSemanaStrig = getDiaDaSemanaStrig;
// Gerar slot de acordo ao horario de funcionamento
const gerarSlots = (data, abre, fecha) => {
    const slots = [];
    const [ano, mes, dia] = data.split('-').map(Number);
    const horaInicio = parseInt(abre.split(':')[0]);
    const horaFim = parseInt(fecha.split(':')[0]);
    for (let h = horaInicio; h < horaFim; h++) {
        const slotStart = new Date(ano, mes - 1, dia, h, 0, 0);
        const slotEnd = new Date(ano, mes - 1, dia, h + 1, 0, 0);
        slots.push({
            slotStart,
            slotEnd,
            hora: `${h.toString().padStart(2, '0')}:00`,
        });
    }
    return slots;
};
exports.gerarSlots = gerarSlots;
// Pega o dia da semana usando
const getDiaDaSemanaInt = (date) => new Date(date).getDay();
exports.getDiaDaSemanaInt = getDiaDaSemanaInt;
const getAngolaTime = () => {
    return new Date().toLocaleString('en-Us', { timeZone: 'Africa/Luanda' });
};
exports.getAngolaTime = getAngolaTime;
const capitalizeFirstCharacter = (str) => {
    if (str.length === 0) {
        return str; // Return an empty string if input is empty
    }
    const firstChar = str.charAt(0).toUpperCase();
    const restOfString = str.slice(1).toLowerCase(); // Get the rest of the string (excluding the first character)
    return firstChar + restOfString;
};
exports.capitalizeFirstCharacter = capitalizeFirstCharacter;
const createRegex = (pattern) => {
    const accents = {
        a: '[aAÀ-Åà-å]',
        e: '[eEÈ-Ëè-ë]',
        i: '[iIÌ-Ïì-ï]',
        o: '[oOÒ-Öò-ö]',
        u: '[uUÙ-Üù-ü]',
        c: '[cCÇç]',
    };
    const regexPattern = pattern
        .replace(/[aeiouc]/gi, (match) => accents[match.toLowerCase()] || match)
        .replace(/\./g, '\\.');
    return new RegExp(regexPattern, 'i');
};
exports.createRegex = createRegex;
const getDocsURL = async (docsObject) => {
    if (docsObject) {
        const docs = docsObject;
        if (docs) {
            const keys = Object.keys(docs);
            for (const key of keys) {
                let value = docs[key];
                if (value && !(0, validate_url_1.default)(value)) {
                    docs[key] = await (0, aws_1.getURL)(value);
                }
            }
        }
    }
};
exports.getDocsURL = getDocsURL;
const deleteDocs = async (docs) => {
    if (docs) {
        const keys = Object.keys(docs);
        for (const key of keys) {
            let value = docs[key];
            if (value) {
                await (0, aws_1.deleteFile)(value);
            }
        }
    }
};
exports.deleteDocs = deleteDocs;
const createHistoricoActividade = async (action, modelName, modelId, user, description) => {
    if (!user)
        return;
    await prisma_1.prisma.historicoActividade.create({
        data: {
            action,
            modelName,
            modelId,
            userId: user.id,
            cnp: user.funcao === 'CNP',
            description,
        },
    });
};
exports.createHistoricoActividade = createHistoricoActividade;
const validateSignature = (token, rowBody, signature) => {
    let isEqual = true;
    // Create a HMAC-SHA-256 hash
    const hmac = crypto_1.default.createHmac('sha256', token);
    hmac.update(JSON.stringify(rowBody));
    // Get the Hex encoded hash
    const hexEncodedHash = hmac.digest('hex');
    if (signature !== hexEncodedHash) {
        return (isEqual = false);
    }
    return isEqual;
};
exports.validateSignature = validateSignature;
const generateSignature = (payload, token) => {
    // Create a HMAC-SHA-256 hash
    const hmac = crypto_1.default.createHmac('sha256', token);
    hmac.update(JSON.stringify(payload));
    // Get the Hex encoded hash
    const hexEncodedHash = hmac.digest('hex');
    return hexEncodedHash;
};
exports.generateSignature = generateSignature;
const getDateTime = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${day}/${month}/${year} ${hours}:${minutes}`;
};
exports.getDateTime = getDateTime;
function sortBy(sort) {
    if (!sort)
        return [];
    const fields = Array.isArray(sort) ? sort : [sort];
    return fields
        .map((item) => {
        const [field, direction] = item.split(":");
        if (!field)
            return null;
        return [
            field,
            ((direction === null || direction === void 0 ? void 0 : direction.toUpperCase()) === "DESC" ? "DESC" : "ASC"),
        ];
    })
        .filter(Boolean);
}
async function generatePassword(length = 12, char) {
    let password = '';
    if (char) {
        password = char;
    }
    // Caso nao providenciar nenhuma password gera uma
    else {
        const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        const lowercase = 'abcdefghijklmnopqrstuvwxyz';
        const numbers = '0123456789';
        const symbols = '!@#$%^&*';
        const allChars = uppercase + lowercase + numbers + symbols;
        // Ensure required characters are included
        password += uppercase[Math.floor(Math.random() * uppercase.length)];
        password += symbols[Math.floor(Math.random() * symbols.length)];
        password += numbers[Math.floor(Math.random() * numbers.length)];
        password += lowercase[Math.floor(Math.random() * lowercase.length)];
        // Fill the rest of the password
        for (let i = password.length; i < length; i++) {
            password += allChars[Math.floor(Math.random() * allChars.length)];
        }
        password = password
            .split('')
            .sort(() => Math.random() - 0.5)
            .join('');
    }
    const hashPassword = await bcryptjs_1.default.hash(password, 12);
    // Shuffle the password
    return { password, hashPassword };
}
const concatAdress = (rua, bairro, municipio, provincia, pais) => {
    let endereco = [];
    if (rua) {
        endereco.push(rua);
    }
    if (bairro) {
        endereco.push(bairro);
    }
    if (municipio) {
        endereco.push(municipio);
    }
    if (provincia) {
        endereco.push(provincia);
    }
    if (pais) {
        endereco.push(pais);
    }
    return endereco.toString().replace(/,/g, ', ');
};
exports.concatAdress = concatAdress;
const formatDateTime = (data) => {
    return data.toLocaleString('pt-PT', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZone: 'Africa/Luanda',
    });
};
exports.formatDateTime = formatDateTime;
const formatDateCompacted = (date) => {
    const ano = date.getFullYear();
    const mes = String(date.getMonth() + 1).padStart(2, '0');
    const dia = String(date.getDate()).padStart(2, '0');
    return `${ano}${mes}${dia}`;
};
exports.formatDateCompacted = formatDateCompacted;
const formatDateDefault = (date) => {
    const ano = date.getFullYear();
    const mes = String(date.getMonth() + 1).padStart(2, '0');
    const dia = String(date.getDate()).padStart(2, '0');
    return `${ano}-${mes}-${dia}`;
};
exports.formatDateDefault = formatDateDefault;
const getEmailFooter = (cumprimentos = 'Com os melhores cumprimentos') => {
    return `
    <br/>
    <p>
      ${cumprimentos},<br/>
      <b>Equipa novocredito</b> <br />
      <table cellpadding="0" cellspacing="0" style="text-align: center; font-family: Arial, sans-serif; font-size: 14px; color: #555;">
        <tr>
          <td>
            <a href="https://novocredito.com" style="color: #007bff; text-decoration: none; margin-right: 15px;">www.novocredito.com</a>
            |
            <a href="mailto:geral@novocredito.com" style="color: #007bff; text-decoration: none; margin: 0 15px;">geral@novocredito.com</a>
            |
            <a href="http://facebook.com/novocredito" style="color: #007bff; text-decoration: none; margin-left: 15px;">Facebook</a>
          </td>
        </tr>
      </table>
    </p>
  `;
};
exports.getEmailFooter = getEmailFooter;
const horaParaMinuto = (hora) => {
    const [h, m] = hora.split(':').map(Number);
    return h * 60 + m;
};
exports.horaParaMinuto = horaParaMinuto;
const downloadImage = async (url) => {
    const response = await fetch(url);
    const buffer = await response.arrayBuffer();
    return buffer;
};
exports.downloadImage = downloadImage;
const MOEDAS = [
    'AOA', 'USD', 'EUR', 'BRL', 'GBP', 'CAD', 'CNY',
    'JPY', 'ZAR', 'NGN', 'MZN', 'CHF'
];
const formatMoeda = (valor, moeda = 'AOA', locale = 'pt-AO') => {
    return new Intl.NumberFormat(locale, {
        style: 'currency',
        currency: moeda,
    }).format(valor);
};
exports.formatMoeda = formatMoeda;
