/*
 * Copyright 2012-present 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.boot.data.autoconfigure.metrics;

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.data.domain.city.City;
import org.springframework.boot.data.domain.city.CityRepository;
import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
import org.springframework.boot.jdbc.autoconfigure.DataSourceInitializationAutoConfiguration;
import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.jdbc.autoconfigure.JdbcTemplateAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.testsupport.classpath.resources.WithResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;

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

/**
 * Integration tests for {@link DataRepositoryMetricsAutoConfiguration}.
 *
 * @author Phillip Webb
 */
@WithResource(name = "schema.sql", content = """
		CREATE TABLE CITY (
		  id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
		  name VARCHAR(30),
		  country  VARCHAR(30)
		);
		""")
class DataRepositoryMetricsAutoConfigurationIntegrationTests {

	private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
		.withBean(SimpleMeterRegistry.class)
		.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
				DataRepositoryMetricsAutoConfiguration.class, JdbcTemplateAutoConfiguration.class,
				DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class,
				DataSourceInitializationAutoConfiguration.class))
		.withUserConfiguration(TestConfig.class);

	@Test
	void repositoryMethodCallRecordsMetrics() {
		this.contextRunner.run((context) -> {
			context.getBean(CityRepository.class).count();
			MeterRegistry registry = context.getBean(MeterRegistry.class);
			assertThat(registry.get("spring.data.repository.invocations")
				.tag("repository", "CityRepository")
				.timer()
				.count()).isOne();
		});
	}

	@Test
	void doesNotPreventMeterBindersFromDependingUponSpringDataRepositories() {
		this.contextRunner.withUserConfiguration(SpringDataRepositoryMeterBinderConfiguration.class)
			.run((context) -> assertThat(context).hasNotFailed());
	}

	@Configuration(proxyBeanMethods = false)
	@EnableJdbcRepositories(basePackageClasses = City.class)
	static class TestConfig extends AbstractJdbcConfiguration {

	}

	@Configuration(proxyBeanMethods = false)
	static class SpringDataRepositoryMeterBinderConfiguration {

		@Bean
		MeterBinder meterBinder(CityRepository repository) {
			return (registry) -> Gauge.builder("city.count", repository::count);
		}

	}

}
