import {
  getOpaqueConfig,
  OpaqueID,
  OpaqueServer,
  RegistrationRequest
} from '../lib/opaque.mjs'


const cfg = getOpaqueConfig(
  OpaqueID.OPAQUE_P256,
  'OPAQUE demo'
)

    
async function register_init( request, env ) {

  const requestJSON = await request.json()

  const initSerialized = requestJSON[ 'init' ]
  const client_identity = requestJSON[ 'username' ].trim()

  // username is also being used for this demo as server-side credential_identifier
  const credential_identifier = client_identity

  if ( await env.KV.get( credential_identifier ) ) {
	throw new Error( 'username already registered' )
  }

  const registrationRequest = RegistrationRequest.deserialize( cfg, initSerialized )

  const oprf_seed = JSON.parse( env.oprf_seed )
  const server_ake_keypair = JSON.parse( env.server_ake_keypair )
  const server_identity = env.server_identity

  const registrationServer = new OpaqueServer(
    cfg,
    oprf_seed,
    server_ake_keypair,
    server_identity
  )

  const registrationResponse = await registrationServer.registerInit( registrationRequest, credential_identifier )
  if ( registrationResponse instanceof Error) {
    throw new Error( `server failed to registerInit: ${registrationRequest}` )
  }
 
  return new Response( JSON.stringify( {
      message: 'username available, registration envelope enclosed',
      envelope: registrationResponse.serialize()
    } ), {
    headers: { 'Content-Type': 'application/json' }
  } )

}

export { register_init }