import { BadRequestException, Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
import { z, ZodError } from 'zod';

export const SenderSchema = z.object({
  name: z.string().min(6, { message: 'Name must be at least 6 characters long' }),
  email: z.string().email({ message: 'Invalid email address' }),
  phone: z.string()
    .optional()
    .refine(
      (val) => {
        if (!val) return true; // If no phone number provided, validation passes
        // Validate US phone number format (various formats supported)
        const usPhoneRegex = /^(\+?1\s?)?(\(\d{3}\)|\d{3})[\s.-]?\d{3}[\s.-]?\d{4}$/;
        return usPhoneRegex.test(val);
      },
      { message: 'Please enter a valid US phone number' }
    ),
  company: z.string().optional(), // Company is optional
  message: z.string().min(10, { message: 'Comments must be at least 10 characters long' }),
});

@Injectable()
export class AppService {
  constructor(
    private mailerService: MailerService,
  ) {}
  
  async sendMail(mailInfo: {
    name: string,
    email: string,
    phone?: string, // Mark as optional with ?
    company?: string, // Mark as optional with ?
    message: string
  }): Promise<void> {
    try {
      SenderSchema.parse(mailInfo);
    } 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: 'andreas.knuth@gmail.com',
      from: `"Bay Area Affiliates, Inc." <bayarea@bizmatch.net>`,
      subject: `Support Request from ${mailInfo.name}`,
      template: 'contact.hbs',
      context: {
        name: mailInfo.name,
        email: mailInfo.email,
        phone: mailInfo.phone || 'Not provided',
        company: mailInfo.company || 'Not provided',
        message: mailInfo.message
      },
    });
  }
}