using Microsoft.AspNetCore.Mvc;
using System.Text;


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/Pilots/", async () =>
{
    var result = (await Storage.GetInstance()).Pilots.Select(r => new worker_2.Models.Pilots.GetList.PilotResult()
    {
        AeroplaneId = r.AeroplaneId,
        FullName = r.FullName,
        BirthDate = r.BirthDate,
        Experience = r.Experience,
        PilotId = r.PilotId,
    }).ToArray();

    return Results.Ok(result);
})
.WithName("List")
.WithOpenApi();

app.MapGet("/Pilots/{pilotId}", async (Guid pilotId) =>
{
    var pilot = (await Storage.GetInstance()).Pilots.FirstOrDefault(r => r.PilotId == pilotId);
    if (pilot is null)
    {
        return Results.NotFound($"Не найден пилот {pilotId}");
    }

    return Results.Json(new worker_2.Models.Pilots.Get.PilotResult()
    {
        AeroplaneId = pilot.AeroplaneId,
        FullName = pilot.FullName,
        BirthDate = pilot.BirthDate,
        Experience = pilot.Experience,
        PilotId = pilot.PilotId,
    });
})
.WithName("Get")
.WithOpenApi();

app.MapPost("/Pilots/", async ([FromBody] worker_2.Models.Pilots.Create.PilotForm request) =>
{
    if ((await Storage.GetInstance()).Airoplanes.FirstOrDefault(x => x.AeroplaneId == request.AeroplaneId) is null)
    {
        return Results.NotFound($"Не найден самолет {request.AeroplaneId}");
    }
    Guid pilotId = Guid.NewGuid();
    (await Storage.GetInstance()).Pilots.Add(new PilotDal()
    {
        PilotId = pilotId,
        BirthDate = request.BirthDate,
        AeroplaneId = request.AeroplaneId,
        FullName = request.FullName,
        Experience = request.Experience,
    });

    return Results.Ok(pilotId);
})
.WithName("Create")
.WithOpenApi();

app.MapPatch("/Pilots/{pilotId}", async (Guid pilotId, [FromBody] worker_2.Models.Pilots.Create.PilotForm request) =>
{
    var pilot = (await Storage.GetInstance()).Pilots.FirstOrDefault(r => r.PilotId == pilotId);
    if (pilot is null)
    {
        return Results.NotFound($"Не найден пилот {pilotId}");
    }

    if((await Storage.GetInstance()).Airoplanes.FirstOrDefault(x => x.AeroplaneId == request.AeroplaneId) is null)
    {
        return Results.NotFound($"Не найдена самолет {request.AeroplaneId}");
    }

    if (!string.IsNullOrEmpty(request.FullName))
    {
        pilot.FullName = request.FullName;
    }

    pilot.AeroplaneId = request.AeroplaneId;
    pilot.Experience = request.Experience;
    pilot.BirthDate = request.BirthDate;

    return Results.Ok(pilot);
})
.WithName("Update")
.WithOpenApi();

app.MapDelete("/Pilots/{pilotId}", async (Guid pilotId) =>
{
    var pilot = (await Storage.GetInstance()).Pilots.FirstOrDefault(r => r.PilotId == pilotId);
    if (pilot is null)
    {
        return Results.NotFound($"Не найден пилот {pilotId}");
    }

    (await Storage.GetInstance()).Pilots.Remove(pilot);
    return Results.Ok(pilotId);
})
.WithName("Delete")
.WithOpenApi();

app.Run();


public class PilotDal
{
    public Guid PilotId { get; set; }

    public string FullName { get; set; }

    public Guid AeroplaneId { get; set; }

    public DateTime? BirthDate { get; set; }

    public int Experience { get; set; }
}

public class AiroplaneDal
{
    public Guid AeroplaneId { get; set; }

    public string Name { get; set; }

    public DateTime ProductionDate { get; set; }

    public int Weght { get; set; }

    public int Lenght { get; set; }

}

public class Storage
{
    private static Random rand = new Random();

    public AiroplaneDal[] Airoplanes { get; set; }

    public List<PilotDal> Pilots { get; set; }

    public static Storage Instance { get; set; }

    private Storage() { }


    public static async Task<Storage> GetInstance()
    {
        if(Instance is not null)
        {
            return Instance;
        }

        var client = new HttpClient();
        string reqUrl = $"https://localhost:7027/Aeroplanes/";
        Instance = new Storage();
        Instance.Airoplanes = await client.GetFromJsonAsync<AiroplaneDal[]>(reqUrl);
        Instance.Pilots = new List<PilotDal>()
        {
            new PilotDal() { PilotId = Guid.NewGuid(), BirthDate = DateTime.Today.AddDays(-100), AeroplaneId = Instance.Airoplanes[rand.Next(Instance.Airoplanes.Length)].AeroplaneId, FullName = "Савицкий Александр Вячеславович", Experience = 10 },
            new PilotDal() { PilotId = Guid.NewGuid(), BirthDate = DateTime.Today.AddDays(-150), AeroplaneId = Instance.Airoplanes[rand.Next(Instance.Airoplanes.Length)].AeroplaneId, FullName = "Гайдулян Максим Петрович", Experience = 15 }
        };

        return Instance;
    }
}