namespace DoliMiddlewareApi.Services.Notifications;

public class WebhookSettings
{
    private static readonly string FilePath =
        Path.Combine(AppContext.BaseDirectory, "data", "webhook_url.txt");

    public string? WebhookUrl { get; private set; }

    public WebhookSettings(IConfiguration configuration)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
        // Archivo tiene prioridad sobre config (persiste actualizaciones en caliente)
        if (File.Exists(FilePath))
            WebhookUrl = File.ReadAllText(FilePath).Trim().NullIfEmpty();
        else
            WebhookUrl = configuration["Notifications:WebhookUrl"].NullIfEmpty();
    }

    public void UpdateUrl(string? url)
    {
        WebhookUrl = url.NullIfEmpty();
        if (WebhookUrl is not null)
            File.WriteAllText(FilePath, WebhookUrl);
        else if (File.Exists(FilePath))
            File.Delete(FilePath);
    }
}

file static class StringExtensions
{
    public static string? NullIfEmpty(this string? s) =>
        string.IsNullOrWhiteSpace(s) ? null : s.Trim();
}
