using Lada.Framework.Data.Mappings.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace Ladaer.BackEnd.Infrastructures.DbContextFactory
{
    /// <summary>
    /// Factory để tạo LadaDbContext cho design-time operations (migrations, scaffolding, etc.)
    /// </summary>
    public class LadaDbContextFactory : IDesignTimeDbContextFactory<LadaDbContext>
    {
        public LadaDbContext CreateDbContext(string[] args)
        {
            // Tạo configuration builder để đọc connection string
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            // Lấy connection string
            var connectionString = configuration.GetConnectionString("LadaConnection");
            
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException("Connection string 'LadaConnection' not found in configuration.");
            }

            // Tạo DbContextOptions
            var optionsBuilder = new DbContextOptionsBuilder<LadaDbContext>();
            optionsBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("Ladaer.BackEnd"));

            return new LadaDbContext(optionsBuilder.Options);
        }
    }
}
