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

namespace AsbCloudWebApi.IntegrationTests.Controllers;

public class DrillerControllerTest : BaseIntegrationTest
{
	private readonly IDrillerClient client;

	public DrillerControllerTest(WebAppFactoryFixture factory)
		: base(factory)
	{
		client = factory.GetAuthorizedHttpClient<IDrillerClient>(string.Empty);

        dbContext.CleanupDbSet<Driller>();
        dbContext.CleanupDbSet<Schedule>();
	}

	[Fact]
	public async Task GetByWellIds_returns_success()
	{
        //arrange
		var well1 = CreateWellAsync(2);
        var well2 = CreateWellAsync(3);
        var well3 = CreateWellAsync(4);
        dbContext.Wells.Add(well1);
        dbContext.Wells.Add(well2);
        dbContext.Wells.Add(well3);

        var driller1 = CreateDrillerAsync(1);
        var driller2 = CreateDrillerAsync(2);
        var driller3 = CreateDrillerAsync(3);

        var schedule1= CreateScheduleAsync(well1.Id, driller1);
        var schedule2 = CreateScheduleAsync(well2.Id, driller2);
        var schedule3 = CreateScheduleAsync(well3.Id, driller3);

        dbContext.Schedule.Add(schedule1);
        dbContext.Schedule.Add(schedule2);
        dbContext.Schedule.Add(schedule3);

        await dbContext.SaveChangesAsync();

        ////act
        var idsWells = dbContext.Wells.ToArray().Select(w => w.Id);
        var response = await client.GetAsync(idsWells, CancellationToken.None);

        ////assert
        Assert.NotNull(response.Content);
        Assert.Equal(3, response.Content.Count());
    }

	private static Schedule CreateScheduleAsync(int idWell, Driller driller) => new()
	{
		IdWell = idWell,
		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)),
		Driller = driller
    };

   
    private static Well CreateWellAsync(int idWell) => new()
    {
        Id = idWell,
        IdWellType = 1,
        IdState = 1,
        Caption = $"Скважина {idWell}",
        Latitude = 10,
        Longitude = 20,
        Timezone = Defaults.Timezone,
        IdCluster = 1,
    };

    private static Driller CreateDrillerAsync(int idDriller) => new()
    {
        Id = idDriller,
        Name = idDriller.ToString(),
        Patronymic = idDriller.ToString(),
        Surname= idDriller.ToString()        
    };
}