using MQTTnet;
using MQTTnet.Client;
using backend.Application;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(builder => builder.WithOrigins("*"));

//app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

var configuration = app.Services.GetRequiredService<IConfiguration>();

// Connect via MQTT

Console.WriteLine($"Connecting to MQTT server: {configuration["Mqtt:Host"]}:{configuration["Mqtt:Port"]}...");

var mqttClient = new MqttFactory().CreateMqttClient();

var options = new MqttClientOptionsBuilder()
	.WithTcpServer(configuration["Mqtt:Host"], int.Parse(configuration["Mqtt:Port"]!))
	.WithCredentials(configuration["Mqtt:Username"], configuration["Mqtt:Password"])
	.WithTlsOptions(new MqttClientTlsOptionsBuilder().Build())
	.Build();

await mqttClient.ConnectAsync(options, CancellationToken.None);

ApplicationState.MqttClient = mqttClient;
ApplicationState.DbContext = new DispenserContext();

Console.WriteLine("Connected");

app.Run();

