import { Resend } from "resend";

const apiKey = process.env.RESEND_API_KEY;
export const resend = apiKey ? new Resend(apiKey) : null;

export const DEFAULT_FROM_EMAIL =
  process.env.EMAIL_FROM || "Nigeria Listing <notifications@nigerialisting.com>";

export interface SendEmailOptions {
  to: string | string[];
  subject: string;
  html: string;
  text?: string;
  from?: string;
  replyTo?: string | string[];
}

/**
 * Robust email dispatch helper with Resend SDK
 * Provides automatic fallback logging in local environments
 */
export async function sendEmail({
  to,
  subject,
  html,
  text,
  from = DEFAULT_FROM_EMAIL,
  replyTo,
}: SendEmailOptions): Promise<{ success: boolean; data?: any; error?: string }> {
  const recipients = Array.isArray(to) ? to : [to];

  if (!resend || !apiKey) {
    console.info(
      `[Email Mock Mode - RESEND_API_KEY not configured] To: ${recipients.join(
        ", "
      )} | Subject: "${subject}"`
    );
    return { success: true, data: { id: `mock-${Date.now()}` } };
  }

  try {
    const { data, error } = await resend.emails.send({
      from,
      to: recipients,
      subject,
      html,
      text: text || subject,
      replyTo,
    });

    if (error) {
      console.warn("[Resend API Notice]:", error.message);
      return { success: false, error: error.message };
    }

    return { success: true, data };
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Failed to send email via Resend";
    console.warn("[Resend Send Catch]:", message);
    return { success: false, error: message };
  }
}
