import { Injectable } from '@nestjs/common';
import nodemailer from 'nodemailer';
import { google } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';
import SMTPTransport from 'nodemailer/lib/smtp-transport';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class MailerService {
  private oauth2Client: OAuth2Client;
  private readonly gmailUser: string;

  constructor(private readonly configService: ConfigService) {
    const clientId = this.configService.get<string>('GMAIL_CLIENT_ID');
    const clientSecret = this.configService.get<string>('GMAIL_CLIENT_SECRET');
    const refreshToken = this.configService.get<string>('GMAIL_REFRESH_TOKEN');

    this.gmailUser = this.configService.get<string>('GMAIL_USER')!;

    this.oauth2Client = new google.auth.OAuth2(
      clientId,
      clientSecret,
      'https://developers.google.com/oauthplayground'
    );

    this.oauth2Client.setCredentials({
      refresh_token: refreshToken,
    });
  }

  async sendMail(to: string, subject: string, html: string) {
    const accessToken = await this.oauth2Client.getAccessToken();
    
    const options: SMTPTransport.Options = {
      host: "smtp.gmail.com",
      port: 465,
      secure: true,
      auth: {
        type: "OAuth2",
        user: this.gmailUser,
        clientId: this.configService.get<string>('GMAIL_CLIENT_ID'),
        clientSecret: this.configService.get<string>('GMAIL_CLIENT_SECRET'),
        refreshToken: this.configService.get<string>('GMAIL_REFRESH_TOKEN'),
        accessToken: accessToken?.token || '',
      }
    }

    const transporter = nodemailer.createTransport(options);

    return transporter.sendMail({
      from: `Scheduler ${this.gmailUser}>`,
      to,
      subject,
      html
    })
  }
}