﻿using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Healox.PermissionServer.Domain.Services;

namespace Healox.PermissionServer.EntityFramework.Services;

/// <summary>
/// Implementation of ICorsPolicyService that consults the client configuration for allowed CORS origins.
/// </summary>
/// <seealso cref="PermissionServer.Services.ICorsPolicyService" />
public class CorsPolicyService : ICorsPolicyService
{
    private readonly IHttpContextAccessor _context;
    private readonly ILogger<CorsPolicyService> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="CorsPolicyService"/> class.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="logger">The logger.</param>
    /// <exception cref="ArgumentNullException">context</exception>
    public CorsPolicyService(IHttpContextAccessor context, ILogger<CorsPolicyService> logger)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
        _logger = logger;
    }

    /// <summary>
    /// Determines whether origin is allowed.
    /// </summary>
    /// <param name="origin">The origin.</param>
    /// <returns></returns>
    public async Task<bool> IsOriginAllowedAsync(string origin)
    {
        origin = origin.ToLowerInvariant();

        var corsOrigins = _context.HttpContext.RequestServices.GetRequiredService<IConfiguration>().GetSection("CorsOrigins").AsEnumerable().AsQueryable();

        var query = from o in corsOrigins
                    where o.Value == origin
                    select o;
        
        var isAllowed = await query.AnyAsync();

        _logger.LogDebug("Origin {origin} is allowed: {originAllowed}", origin, isAllowed);

        return isAllowed;
    }
}