import {authBody,authFailure,AuthError,authRequest,assertAuthResult,phoneReady,loginResponse} from '@/lib/customer-auth';
import {normalizePhone,normalizeOtp,normalizeEmail} from '@/lib/auth-input';
import {isAuthUser,isAuthSession,setAuthCookie} from '@/lib/auth-cookies';
import {json} from '@/lib/server';
import {hasTestRegistration,verifyTestRegistration,resendTestRegistration,clearTestRegistration} from '@/lib/registration-sandbox';
export async function POST(request:Request){
 try{
  const body=await authBody(request),phone=normalizePhone(body.phone);
  if(!phone)throw new AuthError('شماره موبایل معتبر وارد کنید؛ برای مثال ۰۹۱۲۱۲۳۴۵۶۷.');
  if(body.action==='send'||body.action==='resend'){
   if(body.intent==='register'&&hasTestRegistration(request))return resendTestRegistration(request,phone);
   await phoneReady();
   const registration=body.action==='resend'&&body.intent==='register';
   const {result,data}=await authRequest(registration?'resend':'otp',registration?{phone,type:'sms'}:{phone,create_user:false,channel:'sms'});
   assertAuthResult(result,data,'ارسال کد انجام نشد. شماره موبایل را بررسی کنید و دوباره تلاش کنید.');
   return json({phone,step:'verify'});
  }
  if(body.action!=='verify')throw new AuthError('درخواست نامعتبر است.');
  const token=normalizeOtp(body.code);if(!token)throw new AuthError('کد تأیید پیامک را وارد کنید؛ حداکثر شش رقم.');
  const sandbox=body.intent==='register'&&hasTestRegistration(request);
  const verified=sandbox?{result:new Response(),data:await verifyTestRegistration(request,phone,token)}:await authRequest('verify',{phone,token,type:'sms'},undefined,'POST',request);
  const {result,data}=verified;assertAuthResult(result,data,'کد تأیید اشتباه است یا اعتبار آن تمام شده است.');
  if(!isAuthSession(data)||!data.user.phone_confirmed_at)throw new AuthError('تأیید شماره موبایل کامل نشد.',401);
  const returnedPhone=normalizePhone(data.user.phone)||normalizePhone(`+${data.user.phone}`);
  if(returnedPhone!==phone)throw new AuthError('تأیید شماره موبایل کامل نشد.',401);
  if(body.intent==='recover'){
   const response=json({step:'reset'});setAuthCookie(response,request,'planck_recovery',data.access_token,600,'/api/auth/recovery');return response;
  }
  let notice:string|undefined;
  const email=normalizeEmail(data.user.user_metadata?.contact_email);
  if(body.intent==='register'&&!data.user.email&&email){
   try{
    const update=await authRequest('user',{email},data.access_token,'PUT');
    if(update.result.ok&&isAuthUser(update.data)){data.user=update.data;notice='شماره موبایل تأیید شد. برای فعال شدن ورود با ایمیل، لینک تأیید ارسال‌شده به ایمیلتان را باز کنید.'}
    else notice='حساب شما با شماره موبایل ساخته شد؛ اتصال ایمیل انجام نشد. از بخش حساب کاربری دوباره تلاش کنید.';
   }catch{notice='حساب شما با شماره موبایل ساخته شد؛ اتصال ایمیل انجام نشد. از بخش حساب کاربری دوباره تلاش کنید.'}
  }
  if(sandbox)notice='حساب آزمایشی ساخته شد؛ تأیید موبایل با کد موقت انجام شده است. '+(notice||'برای ادامه، اطلاعات احراز هویت را تکمیل کنید.');
  const response=await loginResponse(request,data,body.remember===true,notice);if(sandbox)clearTestRegistration(response,request);return response;
 }catch(error){return authFailure(error)}
}
