namespace watcher_monitoring.Configuration;

public class OidcSettings
{
    public bool Enabled { get; set; } = false;

    public string Authority { get; set; } = string.Empty;

    public string ClientId { get; set; } = string.Empty;

    public string ClientSecret { get; set; } = string.Empty;

    public string Scopes { get; set; } = "openid profile email";

    public string CallbackPath { get; set; } = "/signin-oidc";

    public string ClaimUsername { get; set; } = "preferred_username";

    public string ClaimEmail { get; set; } = "email";

    public bool AutoProvisionUsers { get; set; } = true;

    public bool IsValid => Enabled &&
                           !string.IsNullOrWhiteSpace(Authority) &&
                           !string.IsNullOrWhiteSpace(ClientId) &&
                           !string.IsNullOrWhiteSpace(ClientSecret);

    public string[] GetScopes() => Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries);

    public static OidcSettings FromEnvironment()
    {
        return new OidcSettings
        {
            Enabled = GetBoolEnv("OIDC_ENABLED", false),
            Authority = Environment.GetEnvironmentVariable("OIDC_AUTHORITY") ?? string.Empty,
            ClientId = Environment.GetEnvironmentVariable("OIDC_CLIENT_ID") ?? string.Empty,
            ClientSecret = Environment.GetEnvironmentVariable("OIDC_CLIENT_SECRET") ?? string.Empty,
            Scopes = Environment.GetEnvironmentVariable("OIDC_SCOPES") ?? "openid profile email",
            CallbackPath = Environment.GetEnvironmentVariable("OIDC_CALLBACK_PATH") ?? "/signin-oidc",
            ClaimUsername = Environment.GetEnvironmentVariable("OIDC_CLAIM_USERNAME") ?? "preferred_username",
            ClaimEmail = Environment.GetEnvironmentVariable("OIDC_CLAIM_EMAIL") ?? "email",
            AutoProvisionUsers = GetBoolEnv("OIDC_AUTO_PROVISION_USERS", true)
        };
    }

    private static bool GetBoolEnv(string key, bool defaultValue)
    {
        var value = Environment.GetEnvironmentVariable(key);
        if (string.IsNullOrWhiteSpace(value)) return defaultValue;
        return value.Equals("true", StringComparison.OrdinalIgnoreCase) ||
               value.Equals("1", StringComparison.OrdinalIgnoreCase);
    }
}
