using Intentor.Components;
using Intentor.Data;
using Intentor.Logic;
using Intentor.Services;
using Microsoft.EntityFrameworkCore;

namespace Intentor;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Get Home Assistant Supervisor token
        var supervisorToken = Environment.GetEnvironmentVariable("SUPERVISOR_TOKEN")
            ?? throw new InvalidOperationException("SUPERVISOR_TOKEN environment variable is required");

        // Add services to the container.
        builder.Services.AddHttpClient<HomeAssistantService>(client =>
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {supervisorToken}");
        });
        builder.Services.AddSingleton(sp =>
            new HomeAssistantService(sp.GetRequiredService<IHttpClientFactory>().CreateClient(nameof(HomeAssistantService)), supervisorToken));

        builder.Services.AddDbContext<IntentorDbContext>(options =>
            options.UseSqlite(builder.Configuration.GetConnectionString("IntentorDb")));

        builder.Services.AddScoped<IIntentRepository, IntentRepository>();
        builder.Services.AddScoped<IIntentActivationRepository, IntentActivationRepository>();
        builder.Services.AddScoped<IIntentActionExecutor, IntentActionExecutor>();

        builder.Services.AddRazorComponents()
            .AddInteractiveServerComponents();

        var app = builder.Build();

        // Create database file + schema (no migrations tooling required)
        using (var scope = app.Services.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService<IntentorDbContext>();
            db.Database.EnsureCreated();
        }

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
        app.UseHttpsRedirection();

        app.UseAntiforgery();

        app.MapStaticAssets();
        app.MapRazorComponents<App>()
            .AddInteractiveServerRenderMode();

        app.Run();
    }
}