/*
 * Copyright 2014-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.session.hazelcast;

import java.time.Duration;
import java.time.Instant;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.session.MapSession;
import org.springframework.session.hazelcast.Hazelcast4IndexedSessionRepository.HazelcastSession;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Base class for {@link Hazelcast4IndexedSessionRepository} integration tests.
 *
 * @author Eleftheria Stein
 */
abstract class AbstractHazelcast4IndexedSessionRepositoryITests {

	private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";

	@Autowired
	private HazelcastInstance hazelcastInstance;

	@Autowired
	private Hazelcast4IndexedSessionRepository repository;

	@Test
	void createAndDestroySession() {
		HazelcastSession sessionToSave = this.repository.createSession();
		String sessionId = sessionToSave.getId();

		IMap<String, MapSession> hazelcastMap = this.hazelcastInstance
				.getMap(Hazelcast4IndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);

		this.repository.save(sessionToSave);

		assertThat(hazelcastMap.get(sessionId)).isEqualTo(sessionToSave);

		this.repository.deleteById(sessionId);

		assertThat(hazelcastMap.get(sessionId)).isNull();
	}

	@Test
	void changeSessionIdWhenOnlyChangeId() {
		String attrName = "changeSessionId";
		String attrValue = "changeSessionId-value";
		HazelcastSession toSave = this.repository.createSession();
		toSave.setAttribute(attrName, attrValue);

		this.repository.save(toSave);

		HazelcastSession findById = this.repository.findById(toSave.getId());

		assertThat(findById.<String>getAttribute(attrName)).isEqualTo(attrValue);

		String originalFindById = findById.getId();
		String changeSessionId = findById.changeSessionId();

		this.repository.save(findById);

		assertThat(this.repository.findById(originalFindById)).isNull();

		HazelcastSession findByChangeSessionId = this.repository.findById(changeSessionId);

		assertThat(findByChangeSessionId.<String>getAttribute(attrName)).isEqualTo(attrValue);

		this.repository.deleteById(changeSessionId);
	}

	@Test
	void changeSessionIdWhenChangeTwice() {
		HazelcastSession toSave = this.repository.createSession();

		this.repository.save(toSave);

		String originalId = toSave.getId();
		String changeId1 = toSave.changeSessionId();
		String changeId2 = toSave.changeSessionId();

		this.repository.save(toSave);

		assertThat(this.repository.findById(originalId)).isNull();
		assertThat(this.repository.findById(changeId1)).isNull();
		assertThat(this.repository.findById(changeId2)).isNotNull();

		this.repository.deleteById(changeId2);
	}

	@Test
	void changeSessionIdWhenSetAttributeOnChangedSession() {
		String attrName = "changeSessionId";
		String attrValue = "changeSessionId-value";

		HazelcastSession toSave = this.repository.createSession();

		this.repository.save(toSave);

		HazelcastSession findById = this.repository.findById(toSave.getId());

		findById.setAttribute(attrName, attrValue);

		String originalFindById = findById.getId();
		String changeSessionId = findById.changeSessionId();

		this.repository.save(findById);

		assertThat(this.repository.findById(originalFindById)).isNull();

		HazelcastSession findByChangeSessionId = this.repository.findById(changeSessionId);

		assertThat(findByChangeSessionId.<String>getAttribute(attrName)).isEqualTo(attrValue);

		this.repository.deleteById(changeSessionId);
	}

	@Test
	void changeSessionIdWhenHasNotSaved() {
		HazelcastSession toSave = this.repository.createSession();
		String originalId = toSave.getId();
		toSave.changeSessionId();

		this.repository.save(toSave);

		assertThat(this.repository.findById(toSave.getId())).isNotNull();
		assertThat(this.repository.findById(originalId)).isNull();

		this.repository.deleteById(toSave.getId());
	}

	@Test // gh-1076
	void attemptToUpdateSessionAfterDelete() {
		HazelcastSession session = this.repository.createSession();
		String sessionId = session.getId();
		this.repository.save(session);
		session = this.repository.findById(sessionId);
		session.setAttribute("attributeName", "attributeValue");
		this.repository.deleteById(sessionId);
		this.repository.save(session);

		assertThat(this.repository.findById(sessionId)).isNull();
	}

	@Test
	void createAndUpdateSession() {
		HazelcastSession session = this.repository.createSession();
		String sessionId = session.getId();

		this.repository.save(session);

		session = this.repository.findById(sessionId);
		session.setAttribute("attributeName", "attributeValue");

		this.repository.save(session);

		assertThat(this.repository.findById(sessionId)).isNotNull();

		this.repository.deleteById(sessionId);
	}

	@Test
	void createSessionWithSecurityContextAndFindById() {
		HazelcastSession session = this.repository.createSession();
		String sessionId = session.getId();

		Authentication authentication = new UsernamePasswordAuthenticationToken("saves-" + System.currentTimeMillis(),
				"password", AuthorityUtils.createAuthorityList("ROLE_USER"));
		SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
		securityContext.setAuthentication(authentication);
		session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext);

		this.repository.save(session);

		assertThat(this.repository.findById(sessionId)).isNotNull();

		this.repository.deleteById(sessionId);
	}

	@Test
	void createAndUpdateSessionWhileKeepingOriginalTimeToLiveConfiguredOnRepository() {
		final Duration defaultSessionTimeout = Duration.ofSeconds(1800);

		final IMap<String, MapSession> hazelcastMap = this.hazelcastInstance
				.getMap(Hazelcast4IndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);

		HazelcastSession session = this.repository.createSession();
		String sessionId = session.getId();
		this.repository.save(session);

		assertThat(session.getMaxInactiveInterval()).isEqualTo(defaultSessionTimeout);
		assertThat(hazelcastMap.getEntryView(sessionId).getTtl()).isEqualTo(defaultSessionTimeout.toMillis());

		session = this.repository.findById(sessionId);
		session.setLastAccessedTime(Instant.now());
		this.repository.save(session);

		session = this.repository.findById(sessionId);
		assertThat(session.getMaxInactiveInterval()).isEqualTo(defaultSessionTimeout);
		assertThat(hazelcastMap.getEntryView(sessionId).getTtl()).isEqualTo(defaultSessionTimeout.toMillis());
	}

	@Test
	void createAndUpdateSessionWhileKeepingTimeToLiveSetOnSession() {
		final Duration individualSessionTimeout = Duration.ofSeconds(23);

		final IMap<String, MapSession> hazelcastMap = this.hazelcastInstance
				.getMap(Hazelcast4IndexedSessionRepository.DEFAULT_SESSION_MAP_NAME);

		HazelcastSession session = this.repository.createSession();
		session.setMaxInactiveInterval(individualSessionTimeout);
		String sessionId = session.getId();
		this.repository.save(session);

		assertThat(session.getMaxInactiveInterval()).isEqualTo(individualSessionTimeout);
		assertThat(hazelcastMap.getEntryView(sessionId).getTtl()).isEqualTo(individualSessionTimeout.toMillis());

		session = this.repository.findById(sessionId);
		session.setAttribute("attribute", "value");
		this.repository.save(session);

		session = this.repository.findById(sessionId);
		assertThat(session.getMaxInactiveInterval()).isEqualTo(individualSessionTimeout);
		assertThat(hazelcastMap.getEntryView(sessionId).getTtl()).isEqualTo(individualSessionTimeout.toMillis());
	}

}
