import { HttpException, Injectable, Logger } from '@nestjs/common';
import { CreateContactDto } from './dto/create-contact.dto';
import { IContactService } from './interface/contact.interface';
import * as nodemailer from 'nodemailer';
import { ConfigService } from '@nestjs/config';
import { HostType } from 'common/enum/HostType.enum';

@Injectable()
export class ContactService implements IContactService {
  private readonly logger = new Logger(ContactService.name);
  private readonly transporter: nodemailer.Transporter;

  constructor(private readonly configService: ConfigService) {
    this.transporter = nodemailer.createTransport({
      host: this.configService.get<string>('CONTACT_SMTP_HOST'),
      port: this.configService.get<number>('CONTACT_SMTP_PORT'),
      secure: true,
      auth: {
        user: this.configService.get<string>('CONTACT_SMTP_USER'),
        pass: this.configService.get<string>('CONTACT_SMTP_PASSWORD'),
      },
    });
  }

  async sendEmail(data: CreateContactDto): Promise<boolean> {
    try {
      // Validate required fields dynamically based on client type
      if (data.client === HostType.DFUK && !data.subject && !data.firstname) {
        throw new HttpException(' firstname Subject is required for DFUK clients', 400);
      }
      if (data.client === HostType.CAN && (!data.dropdownSelection || !data.additionalDetails)) {
        throw new HttpException('Dropdown selection and additional details are required for CAN clients', 400);
      }

      // Generate subject based on client type
      const subject = data.client === HostType.DFUK ? data.subject : `Inquiry - ${data.dropdownSelection || 'General'}`;

      // Construct email body
      let emailBody = `
                <p><strong>Name:</strong> ${data.client === HostType.DFUK ? data.firstname : `${data.firstname} ${data.lastname}`}</p>
                <p><strong>Phone:</strong> ${data.phone}</p>
                <p><strong>Email:</strong> ${data.email}</p>
                <p><strong>Message:</strong> ${data.body.replace(/\n/g, '<br>')}</p>
            `;

      if (data.client === HostType.CAN) {
        emailBody += `<p><strong>Selected Option:</strong> ${data.dropdownSelection}</p>`;
        emailBody += `<p><strong>Additional Details:</strong> ${data.additionalDetails.replace(/\n/g, '<br>')}</p>`;
      }

      const mailOptions = {
        from: data.email,
        to: this.configService.get<string>('CONTACT_SMTP_USER'),
        subject,
        html: emailBody,
      };

      await this.transporter.sendMail(mailOptions);
      this.logger.log(`Email sent successfully from ${data.email}`);
      return true;
    } catch (error) {
      this.logger.error(`Failed to send email: ${error.message}`, error.stack);
      throw new HttpException('Failed to send email', 500);
    }
  }
}
