import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { Resend } from "https://esm.sh/resend@2.0.0";

const resend = new Resend(Deno.env.get("RESEND_API_KEY"));

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

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

const getEmailTemplate = (type: string, data: any) => {
  switch (type) {
    case 'welcome':
      return {
        subject: '欢迎使用AI购物助手！',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h1 style="color: #2563eb;">欢迎加入AI购物助手！</h1>
            <p>亲爱的 ${data.name || '用户'}，</p>
            <p>感谢您注册我们的AI购物助手平台！现在您可以享受智能化的购物体验。</p>
            <div style="background: #f3f4f6; padding: 20px; border-radius: 8px; margin: 20px 0;">
              <h3>您可以使用以下功能：</h3>
              <ul>
                <li>🤖 AI智能商品推荐</li>
                <li>💬 自然语言商品咨询</li>
                <li>📦 订单状态实时查询</li>
                <li>🛒 便捷的购物车管理</li>
              </ul>
            </div>
            <p>如有任何问题，请随时联系我们的客服团队。</p>
            <p>祝您购物愉快！</p>
            <p style="color: #6b7280; font-size: 14px;">AI购物助手团队</p>
          </div>
        `
      };
    
    case 'verification':
      return {
        subject: '验证您的邮箱地址',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h1 style="color: #2563eb;">邮箱验证</h1>
            <p>请点击下面的按钮验证您的邮箱地址：</p>
            <div style="text-align: center; margin: 30px 0;">
              <a href="${data.verificationUrl}" 
                 style="background: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">
                验证邮箱
              </a>
            </div>
            <p style="color: #6b7280; font-size: 14px;">如果您没有注册账号，请忽略此邮件。</p>
          </div>
        `
      };
    
    case 'order_confirmation':
      return {
        subject: `订单确认 - ${data.orderNumber}`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h1 style="color: #2563eb;">订单确认</h1>
            <p>亲爱的 ${data.customerName}，</p>
            <p>感谢您的订购！您的订单已确认。</p>
            <div style="background: #f3f4f6; padding: 20px; border-radius: 8px; margin: 20px 0;">
              <h3>订单详情：</h3>
              <p><strong>订单号：</strong>${data.orderNumber}</p>
              <p><strong>订单金额：</strong>¥${data.total}</p>
              <p><strong>预计发货：</strong>${data.estimatedDelivery}</p>
            </div>
            <p>我们会及时更新您的订单状态，您也可以在应用中随时查询。</p>
            <p>感谢您的信任！</p>
          </div>
        `
      };
    
    default:
      return {
        subject: data.subject || '来自AI购物助手的消息',
        html: data.html || data.text || '感谢使用AI购物助手！'
      };
  }
};

const handler = async (req: Request): Promise<Response> => {
  // Handle CORS preflight requests
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const { to, subject, html, text, type = 'custom', data = {} }: EmailRequest = await req.json();

    console.log("开始发送邮件:", { to, type, hasApiKey: !!Deno.env.get("RESEND_API_KEY") });

    if (!to) {
      throw new Error('收件人邮箱地址是必需的');
    }

    if (!Deno.env.get("RESEND_API_KEY")) {
      throw new Error('RESEND_API_KEY 未配置');
    }

    let emailContent;
    
    if (type !== 'custom') {
      emailContent = getEmailTemplate(type, data);
    } else {
      emailContent = {
        subject: subject || '来自AI购物助手的消息',
        html: html || text || '感谢使用AI购物助手！'
      };
    }

    console.log("准备发送邮件:", { 
      from: "AI购物助手 <onboarding@resend.dev>",
      to: [to],
      subject: emailContent.subject
    });

    const emailResponse = await resend.emails.send({
      from: "AI购物助手 <onboarding@resend.dev>", // 使用Resend默认测试域名
      to: [to],
      subject: emailContent.subject,
      html: emailContent.html,
    });

    console.log("邮件发送API响应:", emailResponse);

    return new Response(JSON.stringify({
      success: true,
      id: emailResponse.data?.id,
      message: "邮件发送成功",
      debug: emailResponse
    }), {
      status: 200,
      headers: {
        "Content-Type": "application/json",
        ...corsHeaders,
      },
    });
  } catch (error: any) {
    console.error("邮件发送失败详情:", {
      message: (error instanceof Error ? error.message : String(error)),
      stack: error.stack,
      name: error.name,
      code: error.code,
      statusCode: error.statusCode
    });
    
    return new Response(JSON.stringify({
      success: false,
      error: (error instanceof Error ? error.message : String(error)) || "邮件发送失败",
      details: {
        name: error.name,
        code: error.code,
        statusCode: error.statusCode
      }
    }), {
      status: 500,
      headers: { 
        "Content-Type": "application/json", 
        ...corsHeaders 
      },
    });
  }
};

serve(handler);