"use server";

interface EmailOptions {
  to: string;
  subject: string;
  html: string;
  from?: string;
}

export async function sendEmail(options: EmailOptions): Promise<{ success: boolean; error?: string }> {
  const apiKey = process.env.SENDGRID_API_KEY;
  if (!apiKey) {
    console.warn("[Email] SendGrid API key not configured, skipping email");
    return { success: true }; // Fail silently in dev
  }

  try {
    const res = await fetch("https://api.sendgrid.com/v3/mail/send", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        personalizations: [{ to: [{ email: options.to }] }],
        from: { email: options.from || "noreply@wasiyat.com", name: "Wasiyat" },
        subject: options.subject,
        content: [{ type: "text/html", value: options.html }],
      }),
    });

    if (!res.ok) {
      const text = await res.text();
      console.error("[Email] SendGrid error:", text);
      return { success: false, error: "Failed to send email" };
    }

    return { success: true };
  } catch (error) {
    console.error("[Email] Send error:", error);
    return { success: false, error: "Failed to send email" };
  }
}
