using eSuite.API.Middleware;
using Microsoft.AspNetCore.Http;
using Moq;
using NUnit.Framework;

namespace eSuite.API.UnitTests.Middleware;

[TestFixture]
public class OptionsMiddlewareUnitTests
{
    private Mock<RequestDelegate> _requestDelegateMock = null!;
    private OptionsMiddleware _optionsMiddleWare = null!;

    [SetUp]
    public void Setup()
    {
        _requestDelegateMock = new Mock<RequestDelegate>();
        _optionsMiddleWare = new OptionsMiddleware(_requestDelegateMock.Object);
    }

    [Test]
    public async Task OptionsMiddleware_WhenCalledWithNonOptionsMethod_CallsNextMiddleWare()
    {
        //Arrange
        var context = new DefaultHttpContext();
        
        
        //Act
        await _optionsMiddleWare.Invoke(context);

        //Assert
        _requestDelegateMock.Verify(x => x.Invoke(context), Times.Once);
    }

    [Test]
    public async Task OptionsMiddleware_WhenCalledWithOptionsMethod_CallsNextMiddleWare()
    {
        //Arrange
        var origin = "TestOrigin";

        var context = new DefaultHttpContext();
        context.Request.Method = "OPTIONS";
        context.Request.Headers.Origin = origin;


        //Act
        await _optionsMiddleWare.Invoke(context);

        //Assert
        _requestDelegateMock.Verify(x => x.Invoke(context), Times.Never);

        Assert.That(context.Response.StatusCode, Is.EqualTo(200));
        Assert.That(context.Response.Headers.AccessControlAllowOrigin.ToString(), Is.EqualTo(origin));
        Assert.That(context.Response.Headers.AccessControlAllowHeaders,
            Is.EqualTo(new[] { "Origin, X-Requested-With, Content-Type, Accept, Authorization" }));
        Assert.That(context.Response.Headers.AccessControlAllowMethods, Is.EqualTo(new[] { "GET, POST, PUT, DELETE, OPTIONS" }));
        Assert.That(context.Response.Headers.AccessControlAllowCredentials, Is.EqualTo(new[] { "true" }));
    }
}