import java.time.Duration

// authentication cookie map
def AUTHENTICATON_URN_TO_COOKIE_MAPPER = [
		'urn:qa.agov.ch:names:tc:authfactor:accessapp'  :     'accessApp',
        'urn:qa.agov.ch:names:tc:authfactor:fido'       :     'securityKey',
		'urn:qa.agov.ch:names:tc:authfactor:eid'        :     'eid'  
]

// Accounting
def requester = session['ch.nevis.auth.saml.request.scoping.requesterId'] ?: 'unknown'
def requestId = session['ch.nevis.auth.saml.request.id'] ?: 'unknown'
def requestedAq = session['agov.requestedRoleLevel'] ?: 'unknown'
def user = session['ch.adnovum.nevisidm.user.extId'] ?: 'unknown'
def credentialType = session['authenticatedWith'] ?: '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 tAuth = System.currentTimeMillis() - (request.getSession(true).getCreationTime().getEpochSecond() * 1000)

LOG.info("Event='AUTHENTICATION', Requester='${requester}', RequestId='${requestId}', RequestedAq=${requestedAq}, User=${user}, CredentialType='${credentialType}', tAuth=${tAuth}ms, SourceIp=${sourceIp}, UserAgent='${userAgent}'")

def session = request.getAuthSession(true)

// BUNDBITBK-4824: Address was missing after bmid verification
def loa_str = session.get('agov.actualRoleLevel')

if(loa_str){
    int loa = loa_str as int

    // Best Token Available only if account's AQlevel is high enough
    if ((session.getAttribute('agov.appAddressRequired') == 'true') && (loa < 200)) {
        LOG.debug("Best Token: Address requested but account has to low AQ (${loa})")
        session.setAttribute('agov.appAddressRequired', 'false')
    }
    if ((session.getAttribute('agov.appSvnrAllowed') == 'true') && (loa < 400)) {
        LOG.debug("Best Token: SVNr requested but account has to low AQ (${loa})")
        session.setAttribute('agov.appSvnrAllowed', 'false')
    }
}

// BUNDBITBK-5005: Set cookie to remember the last authentication method
def agovAuthMethodCookie = "LOGINMETHOD=${AUTHENTICATON_URN_TO_COOKIE_MAPPER[session.getAttribute('authenticatedWith')]}; Domain=${parameters.get('cookie.domain')}; Path=/; Max-Age=1800; SameSite=Strict; Secure; HttpOnly"
response.setHeader('Set-Cookie3', agovAuthMethodCookie)

// delete the login cookie
def agovLoginCookie = "agovLogin=deleted; Domain=${parameters.get('cookie.domain')}; Path=/; Max-Age=0; SameSite=Strict; Secure; HttpOnly"
response.setHeader('Set-Cookie', agovLoginCookie)

response.setResult('ok')
return