File size: 6,044 Bytes
db3d93b
 
 
 
 
 
 
 
 
fcc750f
db3d93b
 
 
 
 
 
 
 
 
fcc750f
db3d93b
 
fcc750f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db3d93b
 
 
 
 
 
fcc750f
db3d93b
 
fcc750f
 
 
db3d93b
fcc750f
 
 
 
 
 
 
db3d93b
 
 
fcc750f
db3d93b
fcc750f
db3d93b
 
 
 
 
 
 
 
 
 
fcc750f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db3d93b
 
 
 
 
 
 
fcc750f
db3d93b
 
fcc750f
 
 
db3d93b
fcc750f
 
 
 
 
 
 
db3d93b
 
 
fcc750f
db3d93b
fcc750f
db3d93b
 
 
add3ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db3d93b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { EmailConfig } from './email.config';

@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name);
  private readonly config: EmailConfig;

  constructor(configService: ConfigService) {
    this.config = new EmailConfig(configService);
  }

  async sendOtpEmail(
    email: string,
    otp: string,
    firstName?: string,
  ): Promise<void> {
    try {
      this.logger.log(`πŸ“§ Attempting to send OTP email to: ${email}`);
      const greeting = firstName ? `Hi ${firstName}` : 'Hello';

      const payload = {
        sender: {
          email: this.config.otpEmail,
          name: 'StreamFlix',
        },
        to: [{ email, name: firstName || email }],
        templateId: this.config.otpTemplateId,
        params: {
          GREETING: greeting,
          OTP: otp,
        },
      };

      this.logger.log('πŸ“§ OTP Email payload:', {
        sender: payload.sender,
        to: payload.to,
        templateId: payload.templateId,
        params: payload.params,
      });

      const response = await fetch('https://api.brevo.com/v3/smtp/email', {
        method: 'POST',
        headers: {
          'api-key': this.config.apiKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      const responseText = await response.text();
      this.logger.log(`πŸ“§ Raw Response: ${responseText}`);

      if (!response.ok) {
        let error;
        try {
          error = JSON.parse(responseText);
        } catch {
          error = responseText;
        }
        this.logger.error('πŸ“§ Failed to send OTP email:', error);
        throw new Error('Failed to send OTP email');
      }

      this.logger.log(`πŸ“§ βœ… OTP email sent successfully to ${email}`);
    } catch (error) {
      this.logger.error('πŸ“§ ❌ Error sending OTP email:', error);
      throw error;
    }
  }

  async sendWelcomeEmail(
    email: string,
    firstName: string,
    lastName: string,
  ): Promise<void> {
    try {
      this.logger.log(`πŸ“§ Attempting to send welcome email to: ${email}`);
      const fullName = `${firstName} ${lastName}`.trim();

      const payload = {
        sender: {
          email: this.config.welcomeEmail,
          name: 'StreamFlix',
        },
        to: [{ email, name: fullName || email }],
        templateId: this.config.welcomeTemplateId,
        params: {
          FIRSTNAME: fullName || firstName || 'User',
        },
      };

      this.logger.log('πŸ“§ Welcome Email payload:', {
        sender: payload.sender,
        to: payload.to,
        templateId: payload.templateId,
        params: payload.params,
      });

      const response = await fetch('https://api.brevo.com/v3/smtp/email', {
        method: 'POST',
        headers: {
          'api-key': this.config.apiKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      const responseText = await response.text();
      this.logger.log(`πŸ“§ Raw Response: ${responseText}`);

      if (!response.ok) {
        let error;
        try {
          error = JSON.parse(responseText);
        } catch {
          error = responseText;
        }
        this.logger.error('πŸ“§ Failed to send welcome email:', error);
        throw new Error('Failed to send welcome email');
      }

      this.logger.log(`πŸ“§ βœ… Welcome email sent successfully to ${email}`);
    } catch (error) {
      this.logger.error('πŸ“§ ❌ Error sending welcome email:', error);
      throw error;
    }
  }

  async send2FACode(
    email: string,
    name: string,
    code: string,
    ipAddress?: string,
    userAgent?: string,
    location?: string,
  ): Promise<void> {
    try {
      this.logger.log(`πŸ“§ Attempting to send 2FA code to: ${email}`);

      const payload = {
        sender: {
          email: this.config.otpEmail,
          name: 'StreamFlix Security',
        },
        to: [{ email, name: name || email }],
        templateId: parseInt(process.env.BREVO_2FA_CODE_TEMPLATE_ID || '4', 10),
        params: {
          adminName: name,
          verificationCode: code,
          expiryMinutes: process.env.TWO_FA_CODE_EXPIRY_MINUTES || '10',
          location: location || 'Unknown Location',
          ipAddress: ipAddress || 'Unknown',
          deviceInfo: userAgent || 'Unknown device',
          timestamp: new Date().toLocaleString('en-US', {
            dateStyle: 'long',
            timeStyle: 'short',
          }),
          supportUrl: process.env.SUPPORT_URL || '#',
          securityUrl: process.env.SECURITY_URL || '#',
          privacyUrl: process.env.PRIVACY_URL || '#',
          currentYear: new Date().getFullYear().toString(),
          companyAddress: process.env.COMPANY_ADDRESS || '',
        },
      };

      this.logger.log('πŸ“§ 2FA Code Email payload:', {
        sender: payload.sender,
        to: payload.to,
        templateId: payload.templateId,
        params: { ...payload.params, verificationCode: '******' }, // Hide code in logs
      });

      const response = await fetch('https://api.brevo.com/v3/smtp/email', {
        method: 'POST',
        headers: {
          'api-key': this.config.apiKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      const responseText = await response.text();
      this.logger.log(`πŸ“§ Raw Response: ${responseText}`);

      if (!response.ok) {
        let error;
        try {
          error = JSON.parse(responseText);
        } catch {
          error = responseText;
        }
        this.logger.error('πŸ“§ Failed to send 2FA code email:', error);
        throw new Error('Failed to send 2FA code email');
      }

      this.logger.log(`πŸ“§ βœ… 2FA code sent successfully to ${email}`);
    } catch (error) {
      this.logger.error('πŸ“§ ❌ Error sending 2FA code:', error);
      throw error;
    }
  }
}