type SendEmailParams = {
  to: string | string[];
  subject: string;
  text?: string;
  html?: string;
  from?: string;
  cc?: string | string[];
  bcc?: string | string[];
  attachments?: Array<{
    filename: string;
    content: string; // base64 encoded
    type?: string;
  }>;
};

import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";

const RESEND_API_KEY = process.env.RESEND_API_KEY;
const DEFAULT_FROM = process.env.EMAIL_FROM || "Stargirlnails <no-reply@stargirlnails.de>";

// Cache for AGB PDF to avoid reading it multiple times
let cachedAGBPDF: string | null = null;

async function getAGBPDFBase64(): Promise<string | null> {
  if (cachedAGBPDF) return cachedAGBPDF;
  
  try {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const agbPath = resolve(__dirname, "../../../AGB.pdf");
    const buf = await readFile(agbPath);
    cachedAGBPDF = buf.toString('base64');
    return cachedAGBPDF;
  } catch (error) {
    console.warn("Could not read AGB.pdf:", error);
    return null;
  }
}

export async function sendEmail(params: SendEmailParams): Promise<{ success: boolean }> {
  if (!RESEND_API_KEY) {
    // In development or if not configured, skip sending but don't fail the flow
    console.warn("Resend API key not configured. Skipping email send.");
    return { success: false };
  }

  const response = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${RESEND_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: params.from || DEFAULT_FROM,
      to: Array.isArray(params.to) ? params.to : [params.to],
      subject: params.subject,
      text: params.text,
      html: params.html,
      cc: params.cc ? (Array.isArray(params.cc) ? params.cc : [params.cc]) : undefined,
      bcc: params.bcc ? (Array.isArray(params.bcc) ? params.bcc : [params.bcc]) : undefined,
      attachments: params.attachments,
    }),
  });

  if (!response.ok) {
    const body = await response.text().catch(() => "");
    console.error("Resend send error:", response.status, body);
    return { success: false };
  }
  return { success: true };
}

export async function sendEmailWithAGB(params: SendEmailParams): Promise<{ success: boolean }> {
  const agbBase64 = await getAGBPDFBase64();
  
  if (agbBase64) {
    params.attachments = [
      ...(params.attachments || []),
      {
        filename: "AGB_Stargirlnails_Kiel.pdf",
        content: agbBase64,
        type: "application/pdf"
      }
    ];
  }
  
  return sendEmail(params);
}

export async function sendEmailWithInspirationPhoto(
  params: SendEmailParams, 
  photoData: string, 
  customerName: string
): Promise<{ success: boolean }> {
  if (!photoData) {
    return sendEmail(params);
  }

  // Extract file extension from base64 data URL
  const match = photoData.match(/data:image\/([^;]+);base64,(.+)/);
  if (!match) {
    console.warn("Invalid photo data format");
    return sendEmail(params);
  }

  const [, extension, base64Content] = match;
  const filename = `inspiration_${customerName.replace(/[^a-zA-Z0-9]/g, '_')}_${Date.now()}.${extension}`;

  // Check if attachment is too large (max 1MB base64 content)
  if (base64Content.length > 1024 * 1024) {
    console.warn(`Photo attachment too large: ${base64Content.length} chars, skipping attachment`);
    return sendEmail(params);
  }

  // console.log(`Sending email with photo attachment: ${filename}, size: ${base64Content.length} chars`);

  params.attachments = [
    ...(params.attachments || []),
    {
      filename,
      content: base64Content,
      type: `image/${extension}`
    }
  ];
  
  return sendEmail(params);
}


