using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Managing.Application.Shared;

public interface IAdminConfigurationService
{
    bool IsUserAdmin(string userName);
    List<string> GetAdminUserNames();
}

public class AdminConfigurationService : IAdminConfigurationService
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<AdminConfigurationService> _logger;

    public AdminConfigurationService(IConfiguration configuration, ILogger<AdminConfigurationService> logger)
    {
        _configuration = configuration;
        _logger = logger;
    }

    public bool IsUserAdmin(string userName)
    {
        if (string.IsNullOrEmpty(userName))
        {
            return false;
        }

        var adminUserNames = GetAdminUserNames();
        var isAdmin = adminUserNames.Contains(userName, StringComparer.OrdinalIgnoreCase);
        
        if (isAdmin)
        {
            _logger.LogInformation("User {UserName} has admin privileges", userName);
        }
        
        return isAdmin;
    }

    public List<string> GetAdminUserNames()
    {
        var adminUsers = _configuration["AdminUsers"];
        if (string.IsNullOrEmpty(adminUsers))
        {
            _logger.LogDebug("No admin users configured. Set AdminUsers environment variable.");
            return new List<string>();
        }

        return adminUsers.Split(';', StringSplitOptions.RemoveEmptyEntries)
                       .Select(u => u.Trim())
                       .Where(u => !string.IsNullOrEmpty(u))
                       .ToList();
    }
}
