/*
 * Copyright 2017-2019 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 com.google.cloud.spring.security.iap;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.Jwt;

/**
 * Spring context needed to exercise {@link AudienceValidator}'s {@code afterPropertiesSet()}.
 *
 * @since 1.1
 */
class AudienceValidatorTests {

  private ApplicationContextRunner contextRunner =
      new ApplicationContextRunner()
          .withConfiguration(AutoConfigurations.of(TestConfiguration.class));

  @Test
  void testNullAudienceDisallowedInConstructor() {

    assertThatThrownBy(() -> new AudienceValidator(null))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessage("Audience Provider cannot be null");
  }

  @Test
  void testCorrectAudienceMatches() {
    Jwt mockJwt = Mockito.mock(Jwt.class);
    when(mockJwt.getAudience()).thenReturn(Arrays.asList("cats"));

    this.contextRunner.run(
        context -> {
          AudienceValidator validator = context.getBean(AudienceValidator.class);
          assertThat(validator.validate(mockJwt).hasErrors()).isFalse();
        });
  }

  @Test
  void testWrongAudienceDoesNotMatch() {
    Jwt mockJwt = Mockito.mock(Jwt.class);
    when(mockJwt.getAudience()).thenReturn(Arrays.asList("dogs"));

    this.contextRunner.run(
        context -> {
          AudienceValidator validator = context.getBean(AudienceValidator.class);
          assertThat(validator.validate(mockJwt).hasErrors()).isTrue();
        });
  }

  /** Configuration for the tests. */
  @Configuration
  static class TestConfiguration {
    @Bean
    AudienceValidator audienceValidator() {
      return new AudienceValidator(() -> "cats");
    }
  }
}
