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

        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) {
          return <MailerOptions>{
            transport: {
              host,
              port,
              secure: true, // use SSL
              service: 'gmail',
              auth: {
                type: 'OAuth2',
                user: null,
                clientId: null,
                clientSecret: null,
                accessToken: null,
              },
            },
          };
        }
      },
      inject: [AppConfigService],
    }),
  ],
  providers: [MailService, AppConfigService],
  exports: [MailService, AppConfigService],
})
export class MailModule {}
