using Aberwyn.Models;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System.IO;
using System.Text.Json;
using Microsoft.Extensions.Hosting;

namespace Aberwyn.Data
{
    // SetupService.cs
    public class SetupService
    {
        private readonly IWebHostEnvironment _env;
        private readonly string _filePath;

        public SetupService(IWebHostEnvironment env)
        {
            _env = env;
            _filePath = Path.Combine(_env.ContentRootPath, "infrastructure", "setup.json");
        }


        public SetupSettings GetSetup()
        {
            if (!File.Exists(_filePath))
                return new SetupSettings { IsConfigured = false };

            var json = File.ReadAllText(_filePath);
            return JsonSerializer.Deserialize<SetupSettings>(json) ?? new SetupSettings { IsConfigured = false };
        }


        internal static IServiceProvider BuildTemporaryServices(string connectionString)
        {
            var services = new ServiceCollection();

            // Konfigurera EF + Identity
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Lägg till en tom konfiguration för att undvika null
            services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());

            // Valfritt: Lägg till loggning om något kräver det
            services.AddLogging();

            return services.BuildServiceProvider();
        }

        public static class SetupLoader
        {
            public static SetupSettings Load(IHostEnvironment env)
            {
                var path = Path.Combine(env.ContentRootPath, "infrastructure", "setup.json");
                var json = File.ReadAllText(path);
                return JsonSerializer.Deserialize<SetupSettings>(json)!;
            }

            public static string GetConnectionString(SetupSettings setup)
            {
                return $"server={setup.DbHost};port={setup.DbPort};database={setup.DbName};user={setup.DbUser};password={setup.DbPassword}";
            }
        }

    }

}
