const express = require('express');
const NodeRSA = require('node-rsa');
const bodyParser = require('body-parser');

const app = express();
const PORT = 8761;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const base64Key = "rxHJAejXwDpyWwjsMzL7D1WJ/rDCaiqvsiiHZA+8nnVHVD65oWB9HH1O+ONuhhSblWBNKB0YWeA47cS0JisTizZAvXHfRNC2Sp9ZnSQvtA67GKPZsTsvOS2AlrExvYHc7ibwVVvLoz/ByJV/N7w5lBABmu57aFuIa4GEWPfb677dqnv695D1qlbJwTI+BjPk/OPHXuudYG1bi1uE7goqStX/fL6D0joXnzzMzs2ZdUKMAV/zC/kaILlAe5qA1q3aQQfd8h+gkYCskjfOrp38abNCe/DFXceq9qQ3R5YkviCxQAZJBZYzD1FjtTsOG7xIV4uoQLJjHzsJaQLkDdrwYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAE=";

function loadPublicKey(base64Key) {
    const keyBuffer = Buffer.from(base64Key, 'base64');

    const keyHex = keyBuffer.toString('hex');

    const modulusHex = keyHex.substring(0, 512);
    const exponentHex = keyHex.substring(keyHex.length - 6);

    const modulus = Buffer.from(modulusHex, 'hex');
    const exponent = parseInt(exponentHex, 16);

    const key = new NodeRSA();
    key.importKey({
        n: modulus,
        e: exponent
    }, 'components-public');

    key.setOptions({ encryptionScheme: 'pkcs1_oaep' });

    return key;
}

const publicKey = loadPublicKey(base64Key);

function validarCC(cc) {
    const regex = /^[0-9]{15,16}$/;
    return regex.test(cc);
}

app.get('/', (req, res) => {
    const cc = req.query.cc;

    if (!cc) {
        return res.status(400).send('Parâmetro "cc" é obrigatório.');
    }

    const ccLimpo = cc.replace(/\s+/g, '');

    if (!validarCC(ccLimpo)) {
        return res.status(400).send('Cartão inválido. Certifique-se de que possui 15 ou 16 dígitos.');
    }

    const dataToEncrypt = '00000000' + ccLimpo;

    try {
        const encrypted = publicKey.encrypt(dataToEncrypt, 'base64');
        return res.send(encrypted);
    } catch (error) {
        console.error('Erro na criptografia:', error);
        return res.status(500).send('Erro ao criptografar o cartão.');
    }
});

app.listen(PORT, () => {
    console.log(`Servidor rodando na porta ${PORT}`);
});
