import { MailerService } from '@nestjs-modules/mailer';
import { BadRequestException, Injectable } from '@nestjs/common';
import path, { join } from 'path';
import { fileURLToPath } from 'url';
import { ZodError } from 'zod';
import { SenderSchema } from '../models/db.model.js';
import { ErrorResponse, MailInfo, isEmpty } from '../models/main.model.js';
import { UserService } from '../user/user.service.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

@Injectable()
export class MailService {
  constructor(
    private mailerService: MailerService,
    private userService: UserService,
  ) {}

  async sendInquiry(mailInfo: MailInfo): Promise<void | ErrorResponse> {
    try {
      const validatedSender = SenderSchema.parse(mailInfo.sender);
    } catch (error) {
      if (error instanceof ZodError) {
        const formattedErrors = error.errors.map(err => ({
          field: err.path.join('.'),
          message: err.message,
        }));
        throw new BadRequestException(formattedErrors);
      }
      throw error;
    }
    const user = await this.userService.getUserByMail(mailInfo.email);
    if (isEmpty(mailInfo.sender.name)) {
      return { fields: [{ fieldname: 'name', message: 'Required' }] };
    }
    await this.mailerService.sendMail({
      to: user.email,
      from: '"Bizmatch Team" <info@bizmatch.net>', // override default from
      subject: `Inquiry from ${mailInfo.sender.name}`,
      //template: './inquiry', // `.hbs` extension is appended automatically
      template: join(__dirname, '../..', 'mail/templates/inquiry.hbs'),
      context: {
        // ✏️ filling curly brackets with content
        name: user.firstname,
        inquiry: mailInfo.sender.comments,
        internalListingNumber: mailInfo.listing.internalListingNumber,
        title: mailInfo.listing.title,
        iname: mailInfo.sender.name,
        phone: mailInfo.sender.phoneNumber,
        email: mailInfo.sender.email,
        id: mailInfo.listing.id,
        url: mailInfo.url,
      },
    });
  }
  async sendRequest(mailInfo: MailInfo): Promise<void | ErrorResponse> {
    try {
      const validatedSender = SenderSchema.parse(mailInfo.sender);
    } catch (error) {
      if (error instanceof ZodError) {
        const formattedErrors = error.errors.map(err => ({
          field: err.path.join('.'),
          message: err.message,
        }));
        throw new BadRequestException(formattedErrors);
      }
      throw error;
    }
    await this.mailerService.sendMail({
      to: 'support@bizmatch.net',
      from: `"Bizmatch Support Team" <info@bizmatch.net>`,
      subject: `Support Request from ${mailInfo.sender.name}`,
      //template: './inquiry', // `.hbs` extension is appended automatically
      template: join(__dirname, '../..', 'mail/templates/request.hbs'),
      context: {
        // ✏️ filling curly brackets with content
        request: mailInfo.sender.comments,
        iname: mailInfo.sender.name,
        phone: mailInfo.sender.phoneNumber,
        email: mailInfo.sender.email,
      },
    });
  }
}
