import type { Lang } from "@/lib/catalog";

export function smsConfigured() {
  return Boolean(
    process.env.SMS_API_URL?.trim() &&
      process.env.SMS_API_KEY?.trim() &&
      process.env.SMS_FROM?.trim(),
  );
}

export function appBaseUrl() {
  const raw = process.env.APP_BASE_URL?.trim() || "http://localhost:3000";
  return raw.replace(/\/+$/, "");
}

export function patientUrl(token: string) {
  return `${appBaseUrl()}/p/${token}`;
}

export function buildSmsText(language: Lang, link: string) {
  if (language === "en") {
    return `Your Iran Health file is open. Follow your care here: ${link}`;
  }
  if (language === "ar") {
    return `تم فتح ملفك لدى إيران هلث. تابع مسار خدمتك من هنا: ${link}`;
  }
  return `پرونده شما در ایران هلث ساخته شد. روند خدمت را اینجا ببینید: ${link}`;
}

export function codeTtlMs() {
  const raw = Number(process.env.PATIENT_CODE_TTL_MINUTES ?? "10");
  const minutes = Number.isFinite(raw) ? Math.min(1440, Math.max(1, Math.floor(raw))) : 10;
  return minutes * 60 * 1000;
}

// No vendor is selected. A message is sent only when all three SMS env vars are set.
export async function deliverSms(to: string, text: string) {
  const url = process.env.SMS_API_URL?.trim();
  const key = process.env.SMS_API_KEY?.trim();
  const from = process.env.SMS_FROM?.trim();
  if (!url || !key || !from) return { status: "unsent" as const };
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 10000);
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "content-type": "application/json",
        authorization: `Bearer ${key}`,
      },
      body: JSON.stringify({ to, from, text }),
      signal: controller.signal,
    });
    if (!response.ok) return { status: "failed" as const, error: `HTTP ${response.status}` };
    return { status: "sent" as const };
  } catch {
    return { status: "failed" as const, error: "درخواست پیامک انجام نشد" };
  } finally {
    clearTimeout(timer);
  }
}
