import { Injectable } from '@nestjs/common';
import * as SibApiV3Sdk from '@sendinblue/client';
import { EmailTokensService } from '../email_tokens/email_tokens.service';
import { EmailTemplatesService } from '../email_templates/email_templates.service';
import * as Handlebars from 'handlebars';

@Injectable()
export class EmailService {
  private apiInstance: SibApiV3Sdk.TransactionalEmailsApi;

  constructor(
    private readonly emailTokensService: EmailTokensService,
    private readonly emailTemplatesService: EmailTemplatesService,
  ) {
    this.apiInstance = new SibApiV3Sdk.TransactionalEmailsApi();
    this.apiInstance.setApiKey(
      SibApiV3Sdk.TransactionalEmailsApiApiKeys.apiKey,
      process.env.BREVO_API_KEY,
    );
  }

  private async dispatchEmail(sendSmtpEmail: SibApiV3Sdk.SendSmtpEmail, bypassSafetyShield: boolean = false): Promise<void> {
    const recipient = sendSmtpEmail.to?.[0]?.email;
    if (!recipient) {
      throw new Error('No recipient specified in SMTP email object');
    }

    const whitelist = [
      'saumyajyoti.k@gmail.com',
      'sujit124baral@gmail.com'
    ];

    if (
      !bypassSafetyShield &&
      process.env.DISABLE_EMAIL_SAFETY_SHIELD !== 'true' &&
      process.env.NODE_ENV !== 'production' &&
      !whitelist.includes(recipient.toLowerCase())
    ) {
      console.log(`[EmailService] [SAFETY SHIELD] Blocked sending email to real candidate: ${recipient}. Mocking success.`);
      return;
    }

    await this.apiInstance.sendTransacEmail(sendSmtpEmail);
  }

  /**
   * Send interview schedule confirmation email
   */
  async sendScheduleConfirmation(
    email: string,
    name: string,
    jobTitle: string,
    companyName: string,
    scheduledAt: Date,
    scheduleToken: string,
  ) {
    const interviewLink = `${process.env.FRONTEND_URL}/ai-interview/${scheduleToken}`;

    const templateContext = {
      name,
      jobTitle,
      companyName,
      scheduledAt: scheduledAt.toLocaleString(),
      interviewLink,
    };

    const success = await this.sendTemplateEmail(
      'ai_interview_scheduled',
      email,
      name,
      templateContext,
    );

    if (!success) {
      throw new Error(`Failed to send schedule confirmation email: template 'ai_interview_scheduled' not found or inactive.`);
    }
  }

  /**
   * Send 24-hour reminder email
   */
  async send24HourReminder(
    email: string,
    name: string,
    jobTitle: string,
    companyName: string,
    scheduledAt: Date,
    scheduleToken: string,
  ) {
    const interviewLink = `${process.env.FRONTEND_URL}/ai-interview/${scheduleToken}`;

    const templateContext = {
      name,
      jobTitle,
      companyName,
      scheduledAt: scheduledAt.toLocaleString(),
      interviewLink,
    };

    const success = await this.sendTemplateEmail(
      'ai_interview_24h_reminder',
      email,
      name,
      templateContext,
    );

    if (!success) {
      throw new Error(`Failed to send 24-hour reminder email: template 'ai_interview_24h_reminder' not found or inactive.`);
    }
  }

  /**
   * Send 1-hour reminder email
   */
  async send1HourReminder(
    email: string,
    name: string,
    jobTitle: string,
    companyName: string,
    scheduledAt: Date,
    scheduleToken: string,
  ) {
    const interviewLink = `${process.env.FRONTEND_URL}/ai-interview/${scheduleToken}`;

    const templateContext = {
      name,
      jobTitle,
      companyName,
      scheduledAt: scheduledAt.toLocaleString(),
      interviewLink,
    };

    const success = await this.sendTemplateEmail(
      'ai_interview_1h_reminder',
      email,
      name,
      templateContext,
    );

    if (!success) {
      throw new Error(`Failed to send 1-hour reminder email: template 'ai_interview_1h_reminder' not found or inactive.`);
    }
  }

  /**
   * Send interview completion notification
   */
  async sendCompletionNotification(
    email: string,
    name: string,
    jobTitle: string,
    companyName: string,
    overallScore: number,
  ) {
    const templateContext = {
      name,
      jobTitle,
      companyName,
      overallScore,
      frontendUrl: process.env.FRONTEND_URL,
    };

    const success = await this.sendTemplateEmail(
      'ai_interview_completed',
      email,
      name,
      templateContext,
    );

    if (!success) {
      throw new Error(`Failed to send completion notification email: template 'ai_interview_completed' not found or inactive.`);
    }
  }

  /**
   * Generic method to send an email using a template from the database
   */
  async sendTemplateEmail(
    templateName: string,
    toEmail: string,
    toName: string,
    context: Record<string, any>,
    attachments?: { content: string; name: string }[],
  ): Promise<boolean> {
    try {
      const dbTemplate = await this.emailTemplatesService.findByName(templateName);

      if (!dbTemplate) {
        console.warn(`[EmailService] Template '${templateName}' not found in database. Cannot send email.`);
        return false;
      }

      if (!dbTemplate.is_active) {
        console.log(`[EmailService] Template '${templateName}' is inactive. Email not sent.`);
        return false;
      }

      const sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail();
      sendSmtpEmail.to = [{ email: toEmail, name: toName }];
      sendSmtpEmail.sender = {
        email: process.env.FROM_EMAIL || 'saumyajyoti.k@gmail.com',
        name: process.env.FROM_NAME || 'Jobvumi',
      };

      const mergedContext = {
        playstore_url: 'https://play.google.com/store/apps/details?id=com.jobvumi.jobvumi',
        ...context,
      };

      sendSmtpEmail.subject = Handlebars.compile(dbTemplate.subject)(mergedContext);
      sendSmtpEmail.htmlContent = Handlebars.compile(dbTemplate.body_html)(mergedContext);

      if (attachments && attachments.length > 0) {
        sendSmtpEmail.attachment = attachments;
      }

      const bypassTemplates = [
        'recruiter_profile_approved',
        'recruiter_profile_rejected',
        'recruiter_rejection',
        'registration_welcome_recruiter_approved',
        'registration_welcome_recruiter_pending',
        'recruiter_pending_approval',
      ];
      const shouldBypass = true; // Bypassed all templates for now

      await this.dispatchEmail(sendSmtpEmail, shouldBypass);
      console.log(`[EmailService] Template '${templateName}' sent to ${toEmail}`);
      return true;
    } catch (error) {
      console.error(`[EmailService] Failed to send template '${templateName}' to ${toEmail}:`, error);
      return false;
    }
  }
}
