﻿import { google } from 'googleapis';
import nodemailer from 'nodemailer';

const OAuth2 = google.auth.OAuth2;

interface EmailResult {
  success: boolean;
  message: string;
  messageId?: string;
}

class GmailService {
  private oauth2Client: any;
  private accessToken: string | null = null;

  constructor() {
    this.initializeOAuth();
  }

  private initializeOAuth() {
    this.oauth2Client = new OAuth2(
      process.env.GOOGLE_CLIENT_ID,
      process.env.GOOGLE_CLIENT_SECRET,
      process.env.GOOGLE_REDIRECT_URI || 'https://developers.google.com/oauthplayground'
    );

    this.oauth2Client.setCredentials({
      refresh_token: process.env.GOOGLE_REFRESH_TOKEN,
    });
  }

  private async getAccessToken(): Promise<string> {
    try {
      if (this.accessToken) {
        return this.accessToken;
      }
      const { token } = await this.oauth2Client.getAccessToken();
      this.accessToken = token;
      return token;
    } catch (error) {
      console.error('Failed to get access token:', error);
      throw error;
    }
  }

  async sendEmail(to: string, subject: string, htmlContent: string): Promise<EmailResult> {
    try {
      const accessToken = await this.getAccessToken();

      const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          type: 'OAuth2',
          user: process.env.GMAIL_USER,
          clientId: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET,
          refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
          accessToken: accessToken,
        },
      });

      const mailOptions = {
        from: `"HRMS System" <${process.env.GMAIL_USER}>`,
        to: to,
        subject: subject,
        html: htmlContent,
      };

      const info = await transporter.sendMail(mailOptions);
      console.log(`✅ Email sent to ${to}. Message ID: ${info.messageId}`);
      
      return {
        success: true,
        message: 'Email sent successfully',
        messageId: info.messageId,
      };
    } catch (error) {
      console.error('❌ Failed to send email:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : 'Failed to send email',
      };
    }
  }

  async sendActivationEmail(to: string, name: string, activationToken: string): Promise<EmailResult> {
    const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000';
    const activationLink = `${frontendUrl}/activate-account?token=${activationToken}`;

    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>Activate Your HRMS Account</title>
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px; }
          .header { background: #b828a0; color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
          .button { display: inline-block; padding: 12px 24px; background: #b828a0; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
          .footer { text-align: center; font-size: 12px; color: #666; margin-top: 20px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h2>Welcome to HRMS</h2>
          </div>
          <div style="padding: 20px;">
            <p>Hello <strong>${name}</strong>,</p>
            <p>Your HRMS account has been created!</p>
            <p>Click the button below to activate your account and set your password:</p>
            <div style="text-align: center;">
              <a href="${activationLink}" class="button">Activate Account</a>
            </div>
            <p>Or copy this link: ${activationLink}</p>
            <p><strong>This link expires in 24 hours.</strong></p>
            <p>If you did not request this, please ignore this email.</p>
          </div>
          <div class="footer">
            <p>&copy; ${new Date().getFullYear()} HRMS System. All rights reserved.</p>
          </div>
        </div>
      </body>
      </html>
    `;

    return this.sendEmail(to, '🎉 Activate Your HRMS Account', html);
  }

  async sendTestEmail(): Promise<EmailResult> {
    const html = `
      <!DOCTYPE html>
      <html>
      <head><title>Gmail API Test</title></head>
      <body>
        <h1 style="color: #b828a0;">✅ Gmail API Test Successful!</h1>
        <p>Your HRMS system is now configured with Google's Gmail API.</p>
        <p>You can now send activation emails to new users.</p>
        <hr>
        <p><small>HRMS System</small></p>
      </body>
      </html>
    `;

    return this.sendEmail(process.env.GMAIL_USER!, '✅ Gmail API Test - HRMS', html);
  }
}

export const gmailService = new GmailService();
