import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import { ConfigService } from '@nestjs/config';
import { join } from 'path';
import { readFileSync } from 'fs';

@Injectable()
export class EmailService {
  private transporter: nodemailer.Transporter;

  constructor(private configService: ConfigService) {
    this.transporter = nodemailer.createTransport({
      host: this.configService.get('SMTP_HOST'),
      port: this.configService.get('SMTP_PORT'),
      secure: true,
      auth: {
        user: this.configService.get('SMTP_USER'),
        pass: this.configService.get('SMTP_PASS'),
      },
    });
  }

  private async getEmailTemplate(templateName: string): Promise<string> {
    const templatePath = join(
      __dirname,
      '../../templates/emails',
      `${templateName}.html`
    );
    return readFileSync(templatePath, 'utf-8');
  }

  private async renderTemplate(
    templateName: string,
    context: Record<string, any>,
  ): Promise<string> {
    const template = await this.getEmailTemplate(templateName);
    return template.replace(/{{\s*(.*?)\s*}}/g, (match, key) => {
      return context[key] || '';
    });
  }

  async sendReceiptEmail(
    to: string,
    receiptData: any,
    subject = 'Payment Receipt',
  ): Promise<void> {
    const html = await this.renderTemplate('receipt', {
      ...receiptData,
      company: this.configService.get('COMPANY_NAME'),
      companyEmail: this.configService.get('COMPANY_EMAIL'),
      companyPhone: this.configService.get('COMPANY_PHONE'),
    });

    await this.transporter.sendMail({
      from: this.configService.get('COMPANY_EMAIL'),
      to,
      subject,
      html,
    });
  }

  async sendRefundEmail(
    to: string,
    refundData: any,
    subject = 'Refund Confirmation',
  ): Promise<void> {
    const html = await this.renderTemplate('refund', {
      ...refundData,
      company: this.configService.get('COMPANY_NAME'),
      companyEmail: this.configService.get('COMPANY_EMAIL'),
      companyPhone: this.configService.get('COMPANY_PHONE'),
    });

    await this.transporter.sendMail({
      from: this.configService.get('COMPANY_EMAIL'),
      to,
      subject,
      html,
    });
  }

  async sendPaymentReminder(
    to: string,
    orderData: any,
    subject = 'Payment Reminder',
  ): Promise<void> {
    const html = await this.renderTemplate('reminder', {
      ...orderData,
      company: this.configService.get('COMPANY_NAME'),
      companyEmail: this.configService.get('COMPANY_EMAIL'),
      companyPhone: this.configService.get('COMPANY_PHONE'),
    });

    await this.transporter.sendMail({
      from: this.configService.get('COMPANY_EMAIL'),
      to,
      subject,
      html,
    });
  }

  async sendContactFormNotification(contactData: any): Promise<void> {
    // Send notification to admin about new contact form submission
    const adminEmail = this.configService.get('ADMIN_EMAIL') || this.configService.get('COMPANY_EMAIL');
    
    const html = `
      <h2>New Contact Form Submission</h2>
      <p><strong>Name:</strong> ${contactData.name}</p>
      <p><strong>Email:</strong> ${contactData.email}</p>
      <p><strong>Phone:</strong> ${contactData.phone || 'Not provided'}</p>
      <p><strong>Company:</strong> ${contactData.company || 'Not provided'}</p>
      <p><strong>Service:</strong> ${contactData.service || 'Not specified'}</p>
      <p><strong>Message:</strong></p>
      <p>${contactData.message}</p>
    `;

    await this.transporter.sendMail({
      from: this.configService.get('COMPANY_EMAIL'),
      to: adminEmail,
      subject: 'New Contact Form Submission - Monio Manufacturing',
      html,
    });
  }

  async sendQuoteRequestNotification(quoteData: any): Promise<void> {
    // Send notification to admin about new quote request
    const adminEmail = this.configService.get('ADMIN_EMAIL') || this.configService.get('COMPANY_EMAIL');
    
    const html = `
      <h2>New Quote Request</h2>
      <p><strong>Name:</strong> ${quoteData.name}</p>
      <p><strong>Email:</strong> ${quoteData.email}</p>
      <p><strong>Phone:</strong> ${quoteData.phone}</p>
      <p><strong>Company:</strong> ${quoteData.company}</p>
      <p><strong>Service:</strong> ${quoteData.service}</p>
      <p><strong>Description:</strong></p>
      <p>${quoteData.description}</p>
      <p><strong>Quantity:</strong> ${quoteData.quantity || 'Not specified'}</p>
      <p><strong>Timeline:</strong> ${quoteData.timeline || 'Not specified'}</p>
      <p><strong>Budget:</strong> ${quoteData.budget || 'Not specified'}</p>
    `;

    await this.transporter.sendMail({
      from: this.configService.get('COMPANY_EMAIL'),
      to: adminEmail,
      subject: 'New Quote Request - Monio Manufacturing',
      html,
    });
  }
}
