package cz.muni.fi.pa165.electricityTarifMicroservice.electricityprices;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit.jupiter.SpringExtension;

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

@ExtendWith(SpringExtension.class)
@DataJpaTest
class ElectricityPriceRepositoryTest {
	@Autowired
	private TestEntityManager entityManager;
	@Autowired
	private ElectricityPriceRepository electricityPriceRepository;

	@Test
	void deleteCompany() {
		String companyId1 = "01";
		var price1 = createElectricityPrice(companyId1, 0.0,0.0);

		String companyId2 = "02";
		var price2 = createElectricityPrice(companyId2, 0.0,0.0);

		electricityPriceRepository.deleteCompany(companyId1);

		assertThat(electricityPriceRepository.findAll()).hasSize(1).contains(price2);
		assertThat(electricityPriceRepository.findAll()).hasSize(1).doesNotContain(price1);

		electricityPriceRepository.deleteCompany(companyId2);

		assertThat(electricityPriceRepository.findAll()).hasSize(0);
	}

	@Test
	void averagePriceLowTariff() {
		String companyId1 = "01";
		double lowTariff1 = 300.0;
		createElectricityPrice(companyId1, lowTariff1, 0.0);

		assertThat(electricityPriceRepository.averagePriceLowTariff()).isEqualTo(lowTariff1);

		String companyId2 = "02";
		double lowTariff2 = 200.0;
		createElectricityPrice(companyId2, lowTariff2, 0.0);

		assertThat(electricityPriceRepository.averagePriceLowTariff()).isEqualTo((lowTariff1 + lowTariff2)/2);

		electricityPriceRepository.deleteCompany(companyId1);

		assertThat(electricityPriceRepository.averagePriceLowTariff()).isEqualTo(lowTariff2);

		electricityPriceRepository.deleteCompany(companyId2);
	}

	@Test
	void averagePriceHighTariff() {
		String companyId1 = "01";
		double highTariff1 = 500.0;
		createElectricityPrice(companyId1, 0.0, highTariff1);

		assertThat(electricityPriceRepository.averagePriceHighTariff()).isEqualTo(highTariff1);

		String companyId2 = "02";
		double highTariff2 = 300.0;
		createElectricityPrice(companyId2, 0.0, highTariff2);

		assertThat(electricityPriceRepository.averagePriceHighTariff()).isEqualTo((highTariff1 + highTariff2)/2);

		electricityPriceRepository.deleteCompany(companyId1);

		assertThat(electricityPriceRepository.averagePriceHighTariff()).isEqualTo(highTariff2);

		electricityPriceRepository.deleteCompany(companyId2);
	}

	private ElectricityPrice createElectricityPrice(String companyId, double lowTariff, double highTariff){
		ElectricityPrice price = ElectricityPrice
				.builder()
				.companyId(companyId)
				.priceHighTariff(highTariff)
				.priceLowTariff(lowTariff)
				.build();
		entityManager.persist(price);
		return price;
	}
}