const axios = require('axios');
const fs = require('fs');
const https = require('https');
const moment = require('moment');
const passphrase = '130203';


const httpsAgent = new https.Agent({
    cert: fs.readFileSync('certificado.pem'),
    key: fs.readFileSync('chave.pem'),
    passphrase: passphrase,
    rejectUnauthorized: false,
  });
  
let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: 'https://ehr-auth.saude.gov.br/api/token',
  httpsAgent: httpsAgent,
  headers: { }
};

axios.request(config)
.then((response) => {
  const token = response.data.access_token; 
  const expirationTime = moment().add(30, 'minutes').format('YYYY-MM-DD HH:mm:ss');

 
  const tokenData = `TOKEN: ${token}\nExpiração: ${expirationTime}`;

  
  fs.writeFile('token.txt', tokenData, (err) => {
    if (err) throw err;
    console.log('Token salvo com sucesso no arquivo token.txt');
  });
})
.catch((error) => {
  console.log(error);
});
