import {activeCustomerSession,authBody,authFailure,AuthError} from '@/lib/customer-auth';
import {json} from '@/lib/server';
import {demoCreditInput,demoWalletView,fundingError,fundingId} from '@/lib/wallet-funding';
import {fundingRpc} from '@/lib/wallet-funding-server';
export async function GET(request:Request){try{const {token}=await activeCustomerSession(request);return json(demoWalletView(await fundingRpc('marketplace_demo_wallet',{},token)))}catch(error){return authFailure(error)}}
export async function POST(request:Request){try{
 const body=await authBody(request),{token}=await activeCustomerSession(request);let input;
 try{input=demoCreditInput(body)}catch(error){const [message,status]=fundingError((error as Error).message);throw new AuthError(message,status)}
 const value=await fundingRpc('marketplace_demo_credit',input,token);
 if(typeof value.credited!=='boolean'||typeof value.pending!=='boolean'||typeof value.duplicate!=='boolean'||value.credited!==(value.status==='approved')||value.pending!==(value.status==='pending')||!fundingId(value.review_id)||!['pending','approved','rejected','problem'].includes(String(value.status)))throw new AuthError('پاسخ درخواست معتبر نیست؛ همان درخواست را دوباره بررسی کنید.',502);
 return json({...demoWalletView(value),credited:value.credited===true,pending:value.pending===true,status:value.status,review_id:value.review_id,duplicate:value.duplicate===true});
}catch(error){return authFailure(error)}}
