using CoreLibrary.Exceptions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json;
using Xunit;

namespace UnitTesting
{
    public class CodeCompletExceptionUT
    {
        [Fact]
        public void ExceptionDefaut()
        {
            Assert.ThrowsAsync<CodeCompletException>(() => throw new CodeCompletException());
        }

        [Fact]
        public void ExceptionMessage()
        {
            string message = "Mon super gros problème.";

            Assert.ThrowsAsync<CodeCompletException>(() => throw new CodeCompletException(message));

            try
            {
                throw new CodeCompletException(message);
            }
            catch (CodeCompletException e)
            {
                Assert.Equal(message, e.Message);
            }
        }

        [Fact]
        public void ExceptionMessageEtException()
        {
            string message = "Mon super gros problème.";
            string message2 = "Pas de chance...";
            InvalidOperationException parent = new InvalidOperationException(message2);

            Assert.ThrowsAsync<CodeCompletException>(() => throw new CodeCompletException(message, parent));

            try
            {
                throw new CodeCompletException(message, parent);
            }
            catch (CodeCompletException e)
            {
                Assert.Equal(message, e.Message);
                Assert.NotNull(e.InnerException);
                Assert.IsType<InvalidOperationException>(e.InnerException);
                Assert.Equal(message2, e.InnerException.Message);
            }
        }

        [Fact]
        public void ExceptionSerialisation()
        {
            CodeCompletException exception = new CodeCompletException();

            string jsonString = JsonSerializer.Serialize(exception);
            CodeCompletException? exceptionSerialisee = 
                JsonSerializer.Deserialize<CodeCompletException>(jsonString);

            Assert.NotNull(exceptionSerialisee);
            Assert.Equal(exception.Message, exceptionSerialisee.Message);
        }
    }
}
