using CSR.Infrastructure.Persistence;
using CSR.Application.Services;
using Microsoft.EntityFrameworkCore;


var builder = WebApplication.CreateBuilder(args);

// Get configuration from appsettings.json, environment variables, and Docker secrets in that order
builder.Configuration
  .AddJsonFile("appsettings.json", optional: true)
  .AddEnvironmentVariables()
  .AddKeyPerFile("/run/secrets", optional: true);

// Add services to the container.
builder.Services.AddRazorPages();

// Set up connection to SQLite database
var dbPath = builder.Configuration["Database:Path"];
if (string.IsNullOrEmpty(dbPath))
{
  var folder = Environment.SpecialFolder.LocalApplicationData;
  var path = Environment.GetFolderPath(folder);
  dbPath = Path.Join(path, "csr.db");
}

builder.Services.AddDbContext<CSRDbContext>(options =>
{
  options.UseSqlite($"Data Source={dbPath}");
});


var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
  var services = scope.ServiceProvider;
  var config = services.GetRequiredService<IConfiguration>();

  var context = services.GetRequiredService<CSRDbContext>();
  var userService = services.GetRequiredService<UserService>();

  var adminUsername = config["Admin:Username"] ?? "admin";
  var adminEmail = config["Admin:Email"] ?? "";
  var adminPassword = config["Admin:Password"] ?? "password";

  userService.CreateUser(adminUsername, adminEmail, adminPassword, true);
}

// 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.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
