using AnsonBot.Core;
using Discord.WebSocket;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace AnsonBot.Bot;

/// <summary>
/// Bridges tracker events to a Discord channel. Kept out of the tracker itself
/// so AnsonBot.Core has no dependency on Discord.Net.
/// </summary>
public class PlayerNotificationService : IHostedService
{
    private readonly PlayerTrackerService _tracker;
    private readonly DiscordSocketClient _client;
    private readonly DiscordOptions _options;
    private readonly ILogger<PlayerNotificationService> _logger;

    public PlayerNotificationService(
        PlayerTrackerService tracker,
        DiscordSocketClient client,
        IOptions<DiscordOptions> options,
        ILogger<PlayerNotificationService> logger)
    {
        _tracker = tracker;
        _client = client;
        _options = options.Value;
        _logger = logger;
    }

    public Task StartAsync(CancellationToken ct)
    {
        if (_options.NotificationChannelId == 0)
        {
            _logger.LogInformation(
                "No NotificationChannelId configured; join/leave notifications disabled.");
            return Task.CompletedTask;
        }

        _tracker.PlayerJoined += e => SendAsync($"**{e.Name}** joined the server.");
        _tracker.PlayerLeft += e =>
            SendAsync($"**{e.Name}** left after {Humanize.Duration(e.Duration)}.");

        return Task.CompletedTask;
    }

    private async Task SendAsync(string message)
    {
        if (await _client.GetChannelAsync(_options.NotificationChannelId)
            is not ISocketMessageChannel channel)
        {
            _logger.LogWarning(
                "Channel {Id} not found or not a text channel.", _options.NotificationChannelId);
            return;
        }

        await channel.SendMessageAsync(message);
    }

    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}
