interface EmailOptions {
  to: string;
  subject?: string;
  html?: string;
  text?: string;
  type?: 'welcome' | 'verification' | 'order_confirmation' | 'custom';
  data?: any;
}

interface EmailResponse {
  success: boolean;
  id?: string;
  message?: string;
  error?: string;
}

export class EmailService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = `https://tlsofopqzrzuduinsicm.supabase.co/functions/v1/send-email`;
  }

  async sendEmail(options: EmailOptions): Promise<EmailResponse> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(options),
      });

      const result = await response.json();
      return result;
    } catch (error) {
      console.error('邮件发送错误:', error);
      return {
        success: false,
        error: '邮件发送失败'
      };
    }
  }

  // 发送欢迎邮件
  async sendWelcomeEmail(to: string, name?: string): Promise<EmailResponse> {
    return this.sendEmail({
      to,
      type: 'welcome',
      data: { name }
    });
  }

  // 发送验证邮件
  async sendVerificationEmail(to: string, verificationUrl: string): Promise<EmailResponse> {
    return this.sendEmail({
      to,
      type: 'verification',
      data: { verificationUrl }
    });
  }

  // 发送订单确认邮件
  async sendOrderConfirmation(
    to: string, 
    orderData: {
      orderNumber: string;
      customerName: string;
      total: number;
      estimatedDelivery: string;
    }
  ): Promise<EmailResponse> {
    return this.sendEmail({
      to,
      type: 'order_confirmation',
      data: orderData
    });
  }

  // 发送自定义邮件
  async sendCustomEmail(
    to: string, 
    subject: string, 
    html: string
  ): Promise<EmailResponse> {
    return this.sendEmail({
      to,
      subject,
      html,
      type: 'custom'
    });
  }
}

// 创建邮件服务实例
export const emailService = new EmailService();