import ch.nevis.esauth.auth.engine.AuthResponse

// for autditing
def user = session['ch.adnovum.nevisidm.user.extId'] ?: 'unknown'
def sourceIp = request.getLoginContext()['connection.HttpHeader.X-Real-IP'] ?: 'unknown'
def userAgent = request.getLoginContext()['connection.HttpHeader.user-agent'] ?: request.getLoginContext()['connection.HttpHeader.User-Agent'] ?: 'unknown'

def minLoi = session['agov.op.onboarding.minLoi'] ?: 'unknown'

if (session['agov.op.onboarding.process.state'] == null) {
  // 0) remove SAMLResponse, to avoid multiple processing
  request.getInArgs().remove("SAMLResponse")

  // check status
  if (notes['saml.response.statusCode'] == 'urn:oasis:names:tc:SAML:2.0:status:Success') {

    // we have to do the checks.
    // 1) compare email
    if (!notes['saml.attributes.http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'].equalsIgnoreCase(session['ch.nevis.idm.User.email'])) {
  
      def lasterrorinfo = "email don't match: idm=${session['ch.nevis.idm.User.email']} idp=${notes['saml.attributes.http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress']}"
      response.setNote('lasterror', '9902')
      response.setNote('lasterrorinfo', lasterrorinfo)
  
      LOG.info("Event='OP-FAILED', RequestedAq='${minLoi}', User=${user}, SourceIp=${sourceIp}, UserAgent=${userAgent}, lasterror=${response.getNote('lasterror')}, lasterrorinfo='${lasterrorinfo}'")
  
      response.setStatus(AuthResponse.AUTH_ERROR)
      return
    }
  
    def homeName = notes['saml.attributes.http://schemas.eiam.admin.ch/ws/2013/12/identity/claims/fp/homeName'] ?: 'unknown'
    def subject = session['ch.nevis.auth.saml.assertion.subject'] ?: 'unknown'
    if (homeName == 'unknown' || subject == 'unknown') {
      def lasterrorinfo = "invalid info from IdP: subject=${subject} homeName=${homeName}"
      response.setNote('lasterror', '9903')
      response.setNote('lasterrorinfo', lasterrorinfo)
  
      LOG.info("Event='OP-FAILED', RequestedAq='${minLoi}', User=${user}, SourceIp=${sourceIp}, UserAgent='${userAgent}', lasterror=${response.getNote('lasterror')}, lasterrorinfo='${lasterrorinfo}'")
  
      response.setStatus(AuthResponse.AUTH_ERROR)
      return
    }

    // ok - create the credential
    response.setSessionAttribute('agov.op.onboarding.process.state', 'createCredential')
    response.setSessionAttribute('agov.op.onboarding.homeName', homeName)
    response.setSessionAttribute('agov.op.onboarding.subject', subject)

    response.setSessionAttribute('agov.op.onboarding.subject', session['ch.nevis.auth.saml.assertion.subject'] ?: 'unknown')
    response.setResult('createSamlFedCredential')
    return

  } else {

      def lasterrorinfo = "authentication by IdP failed: ${notes['saml.response.statusCode']}"
      response.setNote('lasterror', '9903')
      response.setNote('lasterrorinfo', lasterrorinfo)
  
      LOG.info("Event='OP-FAILED', RequestedAq='${minLoi}', User=${user}, SourceIp=${sourceIp}, UserAgent='${userAgent}', lasterror=${response.getNote('lasterror')}, lasterrorinfo='${lasterrorinfo}'")
  
      response.setStatus(AuthResponse.AUTH_ERROR)
      return
  }
} else if (session['agov.op.onboarding.process.state'] == 'createCredential') {
  // 2 Credential created, we or done
  def responseId = session['ch.nevis.auth.saml.response.id']
  def homeName = session['agov.op.onboarding.homeName'] ?: 'unknown'
  def subject = session['agov.op.onboarding.subject'] ?: 'unknown'

  LOG.info("Event='OP-SUCCESS', RequestedAq='${minLoi}', User=${user}, SourceIp=${sourceIp}, UserAgent='${userAgent}', ResponseID='${responseId}', subject='${subject}', homeName='${homeName}'")
  response.setResult('done')
  return

} else {
  LOG.error("invalid state: ${session['agov.op.onboarding.process.state']}")
  response.setNote('lasterror', '9909')
  response.setNote('lasterrorinfo', 'internal error')
  response.setResult('failure')
}