namespace MyOffice.Shared;

using Microsoft.Extensions.Configuration;

public static class SharedConfiguration
{
	public const string BaseFileName = "appsettings.shared.json";

	/// <summary>
	/// Adds shared JSON sources to an existing configuration builder (base + environment overlay).
	/// </summary>
	public static IConfigurationBuilder AddSharedAppSettings(
		this IConfigurationBuilder builder,
		string environmentName,
		string? basePath = null,
		bool optional = false,
		bool reloadOnChange = true
	)
	{
		basePath ??= AppContext.BaseDirectory;

		builder
			.AddJsonFile(Path.Combine(basePath, BaseFileName), optional: optional, reloadOnChange: reloadOnChange)
			.AddJsonFile(
				Path.Combine(basePath, $"appsettings.shared.{environmentName}.json"),
				optional: true,
				reloadOnChange: reloadOnChange);

		return builder;
	}

	/// <summary>
	/// Builds a standalone configuration for design-time tools (EF migrations, etc.).
	/// Layering: base shared → environment shared → environment variables.
	/// </summary>
	public static IConfiguration Build(string? environmentName = null)
	{
		environmentName ??= Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
			?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
			?? "Production";

		return new ConfigurationBuilder()
			.SetBasePath(AppContext.BaseDirectory)
			.AddSharedAppSettings(environmentName, optional: false, reloadOnChange: false)
			.AddEnvironmentVariables()
			.Build();
	}
}
