import {AuthError,authFailure} from '@/lib/customer-auth';
import {identitySession,identityRpc} from '@/lib/identity-server';
import {identityUuid,IDENTITY_BUCKET,MAX_IDENTITY_PHOTO} from '@/lib/identity';
import {identityBytes,identityPhotoType,identityPhotoTypes,identityPhotoResponse,identityStorage} from '@/lib/identity-files';
import {sameOrigin,json} from '@/lib/server';
export async function GET(request:Request){try{const {token}=await identitySession(request),url=new URL(request.url),id=url.searchParams.get('id'),kind=url.searchParams.get('kind');if(!identityUuid(id)||!['card','selfie'].includes(kind||''))throw new AuthError('مدرک معتبر نیست.');const d=await identityRpc('marketplace_identity_document',{p_id:id,p_kind:kind},token);return await identityPhotoResponse(d.path,token)}catch(e){return authFailure(e)}}
export async function POST(request:Request){try{
 if(!sameOrigin(request))throw new AuthError('درخواست نامعتبر است.',403);const {token}=await identitySession(request);
 const id=request.headers.get('x-identity-id'),kind=request.headers.get('x-document-kind'),declared=request.headers.get('content-type')?.split(';')[0];
 if(!identityUuid(id)||!['card','selfie'].includes(kind||''))throw new AuthError('مدرک معتبر نیست.');
 if(!identityPhotoTypes.includes(declared||''))throw new AuthError('فقط JPG، PNG یا WebP قابل قبول است.',415);
 if(Number(request.headers.get('content-length')||0)>MAX_IDENTITY_PHOTO)throw new AuthError('حداکثر حجم هر عکس ۵ مگابایت است.',413);
 let bytes;try{bytes=await identityBytes(request.body)}catch{throw new AuthError('فایل خالی یا بزرگ‌تر از ۵ مگابایت است.',413)}
 const type=identityPhotoType(bytes);if(!type||type!==declared)throw new AuthError('فایل عکس معتبر نیست.',415);
 const slot=await identityRpc('marketplace_identity_upload_slot',{p_id:id,p_kind:kind,p_extension:type==='image/jpeg'?'jpg':type==='image/png'?'png':'webp'},token);
 const upload=await identityStorage(`object/${IDENTITY_BUCKET}/${slot.path}`,token,{method:'POST',headers:{'Content-Type':type,'x-upsert':'false'},body:bytes});
 if(!upload.ok)throw new AuthError('بارگذاری انجام نشد. دوباره تلاش کنید.',503);
 if(slot.previous_path)await identityStorage(`object/${IDENTITY_BUCKET}`,token,{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({prefixes:[slot.previous_path]})}).catch(()=>{});
 return json(await identityRpc('marketplace_identity_state',{},token));
}catch(e){return authFailure(e)}}
