import { Module } from '@nestjs/common';
import { MailService } from './mail.service';
import { MailerModule, MailerOptions } from '@nestjs-modules/mailer';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { OAuth2Client } from 'google-auth-library';
@Module({
  imports: [
    MailerModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        const mailConfig = configService.get('googleMailer');
        console.log(mailConfig);

        const clientSecret = mailConfig['clientSecret'];
        const clientId = mailConfig['clientId'];
        const auth = mailConfig['auth'];
        const host = mailConfig['host'];
        const port = +mailConfig['port'];
        try {
          const myOAuth2Client = new OAuth2Client(clientId, clientSecret);
          myOAuth2Client.setCredentials({
            refresh_token: mailConfig['refreshToken'],
          });
          const myAccessTokenObject = await myOAuth2Client.getAccessToken();
          // Access Token sẽ nằm trong property 'token' trong Object mà chúng ta vừa get được ở trên
          const myAccessToken = myAccessTokenObject?.token;
          // const transport = createTransport().get()
          return {
            transport: {
              host,
              port,
              secure: true, // use SSL
              service: 'gmail',
              auth: {
                type: 'OAuth2',
                user: auth.user,
                clientId: clientId,
                clientSecret: clientSecret,
                accessToken: myAccessToken,
              },
            },
          };
        } catch (error) {
          console.log(error);
          return <MailerOptions>{
            transport: {
              host,
              port,
              secure: true, // use SSL
              service: 'gmail',
              auth: {
                type: 'OAuth2',
                user: null,
                clientId: null,
                clientSecret: null,
                accessToken: null,
              },
            },
          };
        }
      },
      inject: [ConfigService],
    }),
  ],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule {}
