import { google } from "googleapis";
import nodemailer from "nodemailer";
import type { AppConfig } from "../config.js";

const OAuth2 = google.auth.OAuth2;

export const createTransporter = (config: AppConfig) => {
  const oauth2Client = new OAuth2(
    config.EMAIL_CLIENT_ID,
    config.EMAIL_CLIENT_SECRET,
    "https://developers.google.com/oauthplayground"
  );

  oauth2Client.setCredentials({
    refresh_token: config.EMAIL_REFRESH_TOKEN,
  });

  const transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 465,
    secure: true,
    auth: {
      type: "OAuth2",
      user: config.EMAIL_USER,
      clientId: config.EMAIL_CLIENT_ID,
      clientSecret: config.EMAIL_CLIENT_SECRET,
      refreshToken: config.EMAIL_REFRESH_TOKEN,
    },
  });

  return transporter;
};
