#!/usr/bin/env node
import { GmailAuthUtils } from '../utils/gmailAuthUtils';
// Or adjust the path/casing as needed to match your project structure.
import { createInterface } from 'readline';
import dotenv from 'dotenv';

dotenv.config();

async function getTokenFromUser() {
  const clientId = process.env.GMAIL_CLIENT_ID;
  const clientSecret = process.env.GMAIL_CLIENT_SECRET;

  if (!clientId || !clientSecret) {
    console.error('Please set GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET in your .env file first.');
    process.exit(1);
  }
  console.log(clientId, clientSecret);
  console.log('\nGenerating Gmail Refresh Token...');
  const authUrl = await GmailAuthUtils.getAuthUrl(clientId, clientSecret);
  console.log('\n1. Visit this URL to authorize the application:');
  console.log(authUrl);
  console.log('\n2. After authorization, you will be redirected to localhost with a code in the URL.');
  console.log('3. Copy the code from the URL and paste it below.\n');

  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  return new Promise<void>((resolve) => {
    rl.question('Enter the code here: ', async (code: string) => {
      const refreshToken = await GmailAuthUtils.getRefreshToken(clientId, clientSecret, code.trim());
      if (refreshToken) {
        console.log('\n✅ Successfully generated refresh token!\n');
        console.log('Add these to your .env file:');
        console.log('----------------------------');
        console.log(`GMAIL_CLIENT_ID=${clientId}`);
        console.log(`GMAIL_CLIENT_SECRET=${clientSecret}`);
        console.log(`GMAIL_REFRESH_TOKEN=${refreshToken}`);
        console.log('----------------------------\n');
      } else {
        console.error('❌ Failed to retrieve refresh token. Please try again.');
      }
      rl.close();
      resolve();
    });
  });
}

getTokenFromUser().catch(console.error);
