import {authBody,authFailure,AuthError,authRequest,assertAuthResult,loginResponse,resolveUsername} from '@/lib/customer-auth';
import {loginIdentifier,validPassword} from '@/lib/auth-input';
export async function POST(request:Request){
 try{
  const body=await authBody(request);const identifier=loginIdentifier(body.identifier??body.email);
  if(!identifier||!validPassword(body.password))throw new AuthError('نام کاربری، ایمیل یا موبایل و رمز عبور را به‌درستی وارد کنید.');
  const credentials='username' in identifier?await resolveUsername(identifier.username):identifier;
  const {result,data}=await authRequest('token?grant_type=password',{...credentials,password:body.password},undefined,'POST',request);
  assertAuthResult(result,data,'ورود انجام نشد. اطلاعات حساب را بررسی کنید.');
  return await loginResponse(request,data,body.remember===true);
 }catch(error){return authFailure(error)}
}
