/**
 * سرویس پیامک کاوه‌نگار (https://kavenegar.com/rest.html)
 * کد تأیید با متد verify/lookup و الگوی ثبت‌شده در پنل کاوه‌نگار ارسال می‌شود.
 */
import type { SmsProvider } from "./provider";

export function kavenegarSms(apiKey: string, otpTemplate: string): SmsProvider {
  const base = `https://api.kavenegar.com/v1/${encodeURIComponent(apiKey)}`;

  async function call(path: string, params: Record<string, string>) {
    const res = await fetch(`${base}/${path}`, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams(params),
      signal: AbortSignal.timeout(10_000),
    });
    const json = (await res.json().catch(() => null)) as { return?: { status: number; message: string } } | null;
    if (!res.ok || json?.return?.status !== 200) {
      throw new Error(`خطای کاوه‌نگار: ${json?.return?.message ?? res.status}`);
    }
  }

  return {
    name: "kavenegar",
    sendOtp: (phone, code) => call("verify/lookup.json", { receptor: phone, token: code, template: otpTemplate }),
    send: (phone, message) => call("sms/send.json", { receptor: phone, message }),
  };
}
