/** Supabase Send SMS hook -> MeliPayamak. No database access. */
import {signedSmsHook,failure,unavailable,limitedText,type SmsOutcome as Outcome} from './sms-webhook.ts';
export {verifySmsSignature} from './sms-webhook.ts';
type Config={hookSecrets:string;username:string;apiKey:string;sender:string;allowedPhone:string};
const ENDPOINT='https://rest.payamak-panel.com/api/SendSMS/SendOtp';
export function meliPhone(value:unknown):string|null{
 if(typeof value!=='string'||!/^\+?[1-9]\d{7,14}$/.test(value))return null;
 const digits=value.replace(/^\+/,'');return /^989\d{9}$/.test(digits)?'0'+digits.slice(2):'+'+digits;
}
/** REST responses may wrap Value/RetStatus, while the documented return is a recId. */
export function meliResult(raw:unknown):Outcome{
 const object=raw&&typeof raw==='object'&&!Array.isArray(raw)?raw as Record<string,unknown>:null;
 const value=object?object.Value:raw;
 if(object&&object.RetStatus!==undefined&&String(object.RetStatus)!=='1')return unavailable();
 if(typeof value!=='string'&&typeof value!=='number')return unavailable();
 if(typeof value==='number'&&!Number.isSafeInteger(value))return unavailable();
 const id=String(value).trim();
 // Short numbers belong to the provider's status/error namespace, not a receipt.
 if(/^\d{4,30}$/.test(id)&&BigInt(id)>BigInt(999))return {ok:true};
 if(['3','4'].includes(id))return failure(429,'محدودیت ارسال پیامک رسیده است. لطفاً کمی بعد دوباره تلاش کنید.');
 if(id==='18'||id==='16')return failure(400,'شماره موبایل برای ارسال پیامک معتبر نیست.');
 if(id==='35')return failure(400,'ارسال پیامک به این شماره امکان‌پذیر نیست. لطفاً از ورود با رمز عبور استفاده کنید.');
 return unavailable();
}
export function melipayamakSmsHook(config:Config){
 const allowedPhone=meliPhone(config.allowedPhone);
 async function deliver(phone:string,otp:string):Promise<Outcome>{
  try{
   const fields=new URLSearchParams({username:config.username,password:config.apiKey,from:config.sender,to:phone,code:String(Number(otp))});
   const result=await fetch(ENDPOINT,{method:'POST',redirect:'error',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:fields.toString(),signal:AbortSignal.timeout(3500)});
   if(!result.ok)return unavailable();
   const raw=await limitedText(result.body,8192);
   let data:unknown;try{data=JSON.parse(raw)}catch{return unavailable()}
   return meliResult(data);
  }catch{return unavailable()}
 }
 return signedSmsHook({
  hookSecrets:config.hookSecrets,
  configured:!!allowedPhone&&!!config.username&&config.username.length<=254&&!!config.apiKey&&config.apiKey.length<=1024&&/^\+?\d{3,20}$/.test(config.sender),
  normalizePhone:value=>{const phone=meliPhone(value);return phone===allowedPhone?phone:null},
  send:deliver
 });
}
