using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using MySqlConnector;

namespace Predictalytics.Infrastructure.Data;

/// <summary>
/// Used only by "dotnet ef" design-time tooling (migrations add/update), never at runtime.
/// Target database is picked via env vars so no connection string/secret ever needs to
/// live in source or config: PREDICTALYTICS_DB_SERVER/_NAME/_USER/_PASSWORD.
/// Falls back to a local dev default if the env vars aren't set.
/// </summary>
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();

        var builder = new MySqlConnectionStringBuilder
        {
            Server = Environment.GetEnvironmentVariable("PREDICTALYTICS_DB_SERVER") ?? "localhost",
            Database = Environment.GetEnvironmentVariable("PREDICTALYTICS_DB_NAME") ?? "Predictalytics",
            UserID = Environment.GetEnvironmentVariable("PREDICTALYTICS_DB_USER") ?? "root",
            Password = Environment.GetEnvironmentVariable("PREDICTALYTICS_DB_PASSWORD") ?? "",
        };

        optionsBuilder.UseMySql(builder.ConnectionString, new MySqlServerVersion(new Version(8, 0, 31)));

        return new AppDbContext(optionsBuilder.Options);
    }
}
