using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Broadcast;
using TeleWave.Application.Broadcast.CreateChannel;
using TeleWave.Application.Broadcast.UpdateChannelSettings;
using TeleWave.Application.Tests.Support;
using TeleWave.Domain.Broadcast;
using TeleWave.Domain.Library;
using TeleWave.Domain.Media;
using Xunit;

namespace TeleWave.Application.Tests.Broadcast;

public class ChannelHandlersTests
{
    private static readonly DateTimeOffset T0 = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);

    [Fact]
    public async Task CreateChannel_Succeeds_AndRejectsDuplicateSlug()
    {
        var fixture = new TestDb();
        await using var db = fixture.New();

        var ok = await new CreateChannelCommandHandler(db).Handle(
            new CreateChannelCommand("News", "news"),
            CancellationToken.None
        );
        Assert.True(ok.IsSuccess);
        await db.SaveChangesAsync(CancellationToken.None);

        var dup = await new CreateChannelCommandHandler(db).Handle(
            new CreateChannelCommand("Other", "news"),
            CancellationToken.None
        );
        Assert.False(dup.IsSuccess);
        Assert.Equal(ChannelErrors.DuplicateSlug, dup.Error);
    }

    [Fact]
    public async Task UpdateChannelSettings_UpdatesBumperChances()
    {
        var fixture = new TestDb();
        var channel = Channel.Create("c", "c", T0);
        await using (var seed = fixture.New())
        {
            seed.Channels.Add(channel);
            await seed.SaveChangesAsync(CancellationToken.None);
        }

        await using var db = fixture.New();
        var result = await new UpdateChannelSettingsCommandHandler(db).Handle(
            new UpdateChannelSettingsCommand(channel.Id, "c2", true, null),
            CancellationToken.None
        );
        Assert.True(result.IsSuccess);
        await db.SaveChangesAsync(CancellationToken.None);

        await using var verify = fixture.New();
        var stored = await verify.Channels.FindAsync(channel.Id);
        Assert.Equal("c2", stored!.Name);
        Assert.True(stored.IsEnabled);
    }
}
