type SendEmailInput = {
  to: string
  subject: string
  html: string
  text?: string
}

type SendEmailResult = {
  ok: boolean
  error?: string
  providerId?: string
}

export async function sendEmail(input: SendEmailInput): Promise<SendEmailResult> {
  const resendApiKey = process.env.RESEND_API_KEY
  const fromEmail = process.env.RESEND_FROM_EMAIL ?? "HU Rooms <rooms@humand.co>"

  if (!resendApiKey) {
    return { ok: false, error: "RESEND_API_KEY is missing" }
  }

  const response = await fetch("https://api.resend.com/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${resendApiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: fromEmail,
      to: [input.to],
      subject: input.subject,
      html: input.html,
      text: input.text,
    }),
  })

  if (!response.ok) {
    const payload = (await response.json().catch(() => null)) as { message?: string } | null
    return { ok: false, error: payload?.message ?? `Email provider error (${response.status})` }
  }

  const payload = (await response.json().catch(() => null)) as { id?: string } | null
  return { ok: true, providerId: payload?.id }
}
