using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudDb.Model;
using AsbCloudWebApi.IntegrationTests.Clients;
using Xunit;

namespace AsbCloudWebApi.IntegrationTests.Controllers;

public class SlipsStatControllerTest : BaseIntegrationTest
{
	private static readonly Schedule schedule = new()
	{
		Id = 1,
		IdDriller = Data.Defaults.Drillers[0].Id,
		IdWell = Data.Defaults.Wells[0].Id,
		ShiftStart = new TimeOnly(8, 0, 0),
		ShiftEnd = new TimeOnly(20, 0, 0),
		DrillStart = new DateTimeOffset(new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
		DrillEnd = new DateTimeOffset(new DateTime(2024, 2, 1, 0, 0, 0, DateTimeKind.Utc))
	};

	private static readonly DetectedOperation detectedOperation = new()
	{
		Id = 1,
		IdTelemetry = Data.Defaults.Telemetries[0].Id,
		IdCategory = WellOperationCategory.IdSlipsTime,
		DateStart = new DateTimeOffset(new DateTime(2024, 1, 23, 15, 0, 0, 0, DateTimeKind.Utc)),
		DateEnd = new DateTimeOffset(new DateTime(2024, 1, 23, 15, 2, 0, 0, DateTimeKind.Utc)),
		ExtraData = new Dictionary<string, object>
		{
			{ "test", 5 }
		}
	};

	private static readonly WellOperation factWellOperation = new()
	{
		Id = 1,
		IdWell = Data.Defaults.Wells[0].Id,
		IdWellSectionType = 1,
		IdCategory = WellOperationCategory.IdRotor,
		IdType = WellOperation.IdOperationTypeFact,
		DepthStart = 0,
		DepthEnd = 100,
		LastUpdateDate = DateTimeOffset.UtcNow,
		DateStart = new DateTimeOffset(new DateTime(2024, 1, 15, 15, 0, 0, DateTimeKind.Utc)),
		DurationHours = 1
	};

	private readonly ISlipsTimeClient client;

	public SlipsStatControllerTest(WebAppFactoryFixture factory)
		: base(factory)
	{
		dbContext.Schedule.Add(schedule);
		dbContext.DetectedOperations.Add(detectedOperation);
		dbContext.WellOperations.Add(factWellOperation);
		dbContext.SaveChanges();

		client = factory.GetAuthorizedHttpClient<ISlipsTimeClient>();
	}

	[Fact]
	public async Task GetAll_returns_success()
	{
		//arrange
		var request = new OperationStatRequest
		{
			DateStartUTC = schedule.DrillStart.DateTime,
			DateEndUTC = schedule.DrillEnd.DateTime,
			DurationMinutesMin = 0,
			DurationMinutesMax = 5
		};

		var dtoExpected = new SlipsStatDto
		{
			DrillerName = $"{Data.Defaults.Drillers[0].Surname} {Data.Defaults.Drillers[0].Name} {Data.Defaults.Drillers[0].Patronymic}",
			WellCount = 1,
			SectionCaption = "Пилотный ствол",
			SlipsCount = 1,
			SlipsTimeInMinutes = (detectedOperation.DateEnd - detectedOperation.DateStart).TotalMinutes,
			SectionDepth = factWellOperation.DepthEnd - factWellOperation.DepthStart,
		};

		//act
		var response = await client.GetAll(request);

		//assert
		Assert.NotNull(response.Content);
		Assert.Single(response.Content);

		var slipsStat = response.Content.First();
		MatchHelper.Match(dtoExpected, slipsStat);
	}
}