using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace JSMR.Infrastructure.Data;

public sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        // adjust base path if needed (points to the worker for secrets/env)
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true)
            .AddJsonFile("appsettings.Development.json", optional: true)
            .AddUserSecrets(typeof(AppDbContextFactory).Assembly, optional: true)
            .AddEnvironmentVariables()
            .Build();

        var conn = config.GetConnectionString("AppDb")
                   ?? throw new InvalidOperationException("Missing ConnectionStrings:AppDb");

        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseMySql(conn, ServerVersion.AutoDetect(conn))
            .EnableSensitiveDataLogging(false)
            .Options;

        return new AppDbContext(options);
    }
}