const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { google } = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.modify'];

const accountName = process.argv[2];
if (!accountName) {
    console.log("Usage: node auth.js <account-name>");
    console.log("Example: node auth.js work");
    process.exit(1);
}

const TOKENS_DIR = path.join(__dirname, 'tokens');
if (!fs.existsSync(TOKENS_DIR)) {
    fs.mkdirSync(TOKENS_DIR);
}

const TOKEN_PATH = path.join(TOKENS_DIR, `${accountName}.json`);

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading credentials.json file. Make sure you downloaded it from Google Cloud Console:', err);
  authorize(JSON.parse(content), getNewToken);
});

function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed || credentials.web;
  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0] || 'urn:ietf:wg:oauth:2.0:oob');

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return callback(oAuth2Client);
    oAuth2Client.setCredentials(JSON.parse(token));
    console.log(`Token for account '${accountName}' already exists and is valid. You don't need to authenticate again.`);
  });
}

function getNewToken(oAuth2Client) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log(`\n=== Authorizing Account: ${accountName} ===\n`);
  console.log('Authorize this app by visiting this url:\n', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('\nEnter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log(`Token stored successfully to ${TOKEN_PATH}`);
      });
    });
  });
}
