const IPPANEL_PATTERN_CODE = process.env.IPPANEL_PATTERN_CODE ?? "bhuf3xmo7k80uhr";
const IPPANEL_TOKEN =
  process.env.IPPANEL_TOKEN ??
  "YTFiNmYzM2MtNTJkNi00ZTFjLTljZDItMDU4YjQwODNiOGU1YWZlNzIwZDBlYTM0Yzg4M2IyMzMzMmRiM2E4ZTVjNTM=";
const IPPANEL_ORIGINATOR = process.env.IPPANEL_ORIGINATOR ?? "+983000505";
const IPPANEL_BASE_URL = process.env.IPPANEL_BASE_URL ?? "https://edge.ippanel.com/v1";

type IppanelPatternResponse = {
  status?: string;
  code?: number;
  message?: string;
  data?: unknown;
};

export async function sendLoginCode(phone: string, code: string) {
  const recipient = phone.startsWith("0") ? `+98${phone.slice(1)}` : phone;

  const response = await fetch(`${IPPANEL_BASE_URL}/api/send`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: IPPANEL_TOKEN,
    },
    body: JSON.stringify({
      sending_type: "pattern",
      from_number: IPPANEL_ORIGINATOR,
      code: IPPANEL_PATTERN_CODE,
      recipients: [recipient],
      params: {
        code,
      },
    }),
  });

  const payload = (await response.json().catch(() => null)) as IppanelPatternResponse | null;

  if (!response.ok) {
    throw new Error(payload?.message || "IPPANEL_SEND_FAILED");
  }

  return payload;
}
