import {applicationOrigin} from '@/lib/application-origin';
import {requireAccountAccess} from '@/lib/account-access-server';
import {authBody,authFailure,AuthError,authRequest,assertAuthResult} from '@/lib/customer-auth';
import {normalizeEmail,validPassword} from '@/lib/auth-input';
import {cookieValue,setAuthCookie,clearSession,isAuthUser} from '@/lib/auth-cookies';
import {json} from '@/lib/server';
/** Restore an unexpired recovery form after reload without creating a login. */
export async function GET(request:Request){try{
 if(request.headers.get('sec-fetch-site')==='cross-site')throw new AuthError('درخواست نامعتبر است.',403);
 const token=cookieValue(request,'planck_recovery');if(!token)throw new AuthError('اعتبار بازیابی تمام شده است. دوباره درخواست بازیابی بدهید.',401);
 const {result,data}=await authRequest('user',undefined,token);
 if(!result.ok||!isAuthUser(data)||!data.email||!data.email_confirmed_at)throw new AuthError('اعتبار بازیابی تمام شده است. دوباره درخواست بازیابی بدهید.',401);
 await requireAccountAccess(token,'login',data.id);
 return json({email:data.email});
}catch(error){return authFailure(error)}}
export async function POST(request:Request){
 try{
  const body=await authBody(request);
  if(body.action==='request'){
   const email=normalizeEmail(body.email);if(!email)throw new AuthError('ایمیل معتبر وارد کنید.');
   const verifier=crypto.randomUUID().replaceAll('-','')+crypto.randomUUID().replaceAll('-','');
   const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(verifier));
   const challenge=btoa(String.fromCharCode(...new Uint8Array(digest))).replaceAll('+','-').replaceAll('/','_').replaceAll('=','');
   const redirect=new URL('/auth/recovery',applicationOrigin(request)).href;
   const {result,data}=await authRequest(`recover?redirect_to=${encodeURIComponent(redirect)}`,{email,code_challenge:challenge,code_challenge_method:'s256'});
   assertAuthResult(result,data,'ارسال لینک بازیابی انجام نشد. بعداً دوباره تلاش کنید.');
   const response=json({message:'اگر این ایمیل حسابی داشته باشد، لینک بازیابی برای آن ارسال می‌شود. لینک را در همین مرورگر باز کنید.'});
   setAuthCookie(response,request,'planck_recovery_verifier',verifier,600,'/auth/recovery','Lax');return response;
  }
  if(body.action!=='reset')throw new AuthError('درخواست نامعتبر است.');
  if(!validPassword(body.password,true))throw new AuthError('رمز جدید باید بین ۱۲ تا ۲۵۶ نویسه باشد.');
  const token=cookieValue(request,'planck_recovery');if(!token)throw new AuthError('اعتبار بازیابی تمام شده است. دوباره درخواست بازیابی بدهید.',401);
  await requireAccountAccess(token);
  const {result,data}=await authRequest('user',{password:body.password},token,'PUT');
  assertAuthResult(result,data,'تغییر رمز انجام نشد. دوباره درخواست بازیابی بدهید.');
  try{await authRequest('logout?scope=global',{},token)}catch{/* Password update succeeded; local recovery access is always cleared below. */}
  const response=json({message:'رمز عبور تغییر کرد. با رمز جدید وارد شوید.'});
  clearSession(response,request);
  setAuthCookie(response,request,'planck_recovery','',0,'/api/auth/recovery');return response;
 }catch(error){return authFailure(error)}
}
