using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
using LanguageExt;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Shouldly;
using Testably.Abstractions.Testing;

namespace ErsatzTV.Tests.Application.Channels;

[TestFixture]
public class DeleteChannelHandlerTests : ChannelHandlerTestBase
{
    private DeleteChannelHandler MakeHandler(MockFileSystem? fileSystem = null) =>
        new(Worker, Db.Factory, fileSystem ?? new MockFileSystem(), SearchTargets);

    [Test]
    public async Task Should_Return_NotFoundError_When_Channel_Missing()
    {
        Either<BaseError, Unit> result = await MakeHandler().Handle(new DeleteChannel(999), CancellationToken.None);

        BaseError error = LeftOf(result);
        error.ShouldBeOfType<NotFoundError>();
    }

    [Test]
    public async Task Should_Delete_Existing_Channel()
    {
        await SeedChannel(1, "5");

        Either<BaseError, Unit> result = await MakeHandler().Handle(new DeleteChannel(1), CancellationToken.None);

        result.IsRight.ShouldBeTrue();

        await using TvContext context = Db.CreateContext();
        bool exists = await context.Channels.AnyAsync(c => c.Id == 1);
        exists.ShouldBeFalse();
    }

    [Test]
    public async Task Should_Delete_Guide_Cache_File_Through_FileSystem_Abstraction()
    {
        await SeedChannel(1, "5");

        var fileSystem = new MockFileSystem();
        string cacheFile = fileSystem.Path.Combine(FileSystemLayout.ChannelGuideCacheFolder, "5.xml");
        fileSystem.Directory.CreateDirectory(FileSystemLayout.ChannelGuideCacheFolder);
        await fileSystem.File.WriteAllTextAsync(cacheFile, "<tv/>");
        fileSystem.File.Exists(cacheFile).ShouldBeTrue();

        Either<BaseError, Unit> result =
            await MakeHandler(fileSystem).Handle(new DeleteChannel(1), CancellationToken.None);

        result.IsRight.ShouldBeTrue();
        // routed through the abstraction (not static File.Delete), so the MockFileSystem observes the removal
        fileSystem.File.Exists(cacheFile).ShouldBeFalse();
    }

    [Test]
    public async Task Should_Delete_System_Owned_Weighted_AutoTune_Artifacts_But_Not_User_Collections()
    {
        await SeedChannel(1, "5");

        await using (TvContext seed = Db.CreateContext())
        {
            // Artifacts owned by channel 1 (a weighted auto-tune channel's MultiCollection + member).
            seed.SmartCollections.Add(
                new ErsatzTV.Core.Domain.SmartCollection
                {
                    Id = 10, Name = "at:owned:0", Query = "type:episode AND show_title:\"A\"", OwnedByChannelId = 1
                });
            seed.MultiCollections.Add(
                new ErsatzTV.Core.Domain.MultiCollection { Id = 20, Name = "at-mc:owned", OwnedByChannelId = 1 });

            // A user's own collections (and another channel's) must survive.
            seed.SmartCollections.Add(
                new ErsatzTV.Core.Domain.SmartCollection { Id = 11, Name = "user-sc", Query = "type:movie" });
            seed.MultiCollections.Add(
                new ErsatzTV.Core.Domain.MultiCollection { Id = 21, Name = "user-mc" });
            seed.MultiCollections.Add(
                new ErsatzTV.Core.Domain.MultiCollection { Id = 22, Name = "at-mc:other", OwnedByChannelId = 2 });
            await seed.SaveChangesAsync();
        }

        Either<BaseError, Unit> result = await MakeHandler().Handle(new DeleteChannel(1), CancellationToken.None);
        result.IsRight.ShouldBeTrue();

        await using TvContext context = Db.CreateContext();
        (await context.SmartCollections.AnyAsync(sc => sc.Id == 10)).ShouldBeFalse();
        (await context.MultiCollections.AnyAsync(mc => mc.Id == 20)).ShouldBeFalse();

        (await context.SmartCollections.AnyAsync(sc => sc.Id == 11)).ShouldBeTrue();
        (await context.MultiCollections.AnyAsync(mc => mc.Id == 21)).ShouldBeTrue();
        (await context.MultiCollections.AnyAsync(mc => mc.Id == 22)).ShouldBeTrue();
    }

    private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
        either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
}
