type Config={supabaseUrl:string;serviceRoleKey:string;directoryToken:string};
const answer=(body:unknown,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}});
export function usernameLookup(config:Config){
 return async(request:Request):Promise<Response>=>{
  if(request.method!=='POST')return answer({error:'method_not_allowed'},405);
  if(config.directoryToken.length<32||!config.serviceRoleKey||!config.supabaseUrl)return answer({error:'not_configured'},503);
  const supplied=request.headers.get('authorization')?.replace(/^Bearer /,'')||'';
  if(supplied.length>512)return answer({error:'unauthorized'},401);
  const hashes=await Promise.all([supplied,config.directoryToken].map(value=>crypto.subtle.digest('SHA-256',new TextEncoder().encode(value))));
  const actual=new Uint8Array(hashes[0]),expected=new Uint8Array(hashes[1]);let difference=0;
  for(let i=0;i<expected.length;i++)difference|=actual[i]^expected[i];
  if(difference)return answer({error:'unauthorized'},401);
  try{
   const reader=request.body?.getReader();if(!reader)return answer({error:'invalid_request'},400);
   let body='',size=0;const decoder=new TextDecoder();
   while(true){const {value,done}=await reader.read();if(done)break;size+=value.byteLength;if(size>2048){await reader.cancel();return answer({error:'too_large'},413)}body+=decoder.decode(value,{stream:true})}
   body+=decoder.decode();const parsed=JSON.parse(body),username=parsed?.username;
   if(typeof username!=='string'||!/^[a-z][a-z0-9_]{2,31}$/.test(username))return answer({error:'invalid_request'},400);
   const response=await fetch(`${config.supabaseUrl.replace(/\/$/,'')}/rest/v1/rpc/marketplace_resolve_login`,{
    method:'POST',headers:{apikey:config.serviceRoleKey,Authorization:`Bearer ${config.serviceRoleKey}`,'Content-Type':'application/json'},
    body:JSON.stringify({login_name:username}),signal:AbortSignal.timeout(10000)
   });
   if(!response.ok)return answer({error:'lookup_unavailable'},503);
   const data=await response.json() as {phone?:unknown;email?:unknown}|null;
   return answer({phone:typeof data?.phone==='string'?data.phone:null,email:typeof data?.email==='string'?data.email:null});
  }catch{return answer({error:'lookup_unavailable'},503)}
 };
}
