using GmRelay.Bot.Infrastructure.Telegram;
using GmRelay.Shared.Platform;

namespace GmRelay.Bot.Features.Sessions.ListSessions;

public sealed record DeleteSessionCommand(
    Guid SessionId,
    long TelegramUserId,
    string CallbackQueryId,
    long ChatId,
    int MessageId);

public sealed class DeleteSessionHandler(
    GmRelay.Shared.Features.Sessions.ListSessions.DeleteSessionHandler sharedHandler,
    GmRelay.Shared.Features.Sessions.ListSessions.ListSessionsHandler listSessionsHandler,
    IPlatformMessenger messenger,
    ILogger<DeleteSessionHandler> logger)
{
    public async Task HandleAsync(DeleteSessionCommand command, CancellationToken ct)
    {
        var platformUser = new PlatformUser(
            PlatformKind.Telegram,
            command.TelegramUserId.ToString(),
            string.Empty,
            null);

        var platformGroup = new PlatformGroup(
            PlatformKind.Telegram,
            command.ChatId.ToString(),
            string.Empty);

        var scheduleMessage = TelegramPlatformIds.Message(command.ChatId, null, command.MessageId);

        var sharedCommand = new GmRelay.Shared.Features.Sessions.ListSessions.DeleteSessionCommand(
            command.SessionId,
            platformUser,
            platformGroup,
            scheduleMessage);

        var result = await sharedHandler.HandleAsync(sharedCommand, ct);

        if (!result.Success)
        {
            await messenger.AnswerInteractionAsync(
                new PlatformInteractionReply(command.CallbackQueryId, result.ReplyText!, result.ReplyText!.Contains("owner")),
                ct);
            return;
        }

        // 4. If no sessions are left in a bot-owned forum topic, delete the topic.
        if (result.ThreadId.HasValue &&
            TelegramTopicRouting.ShouldDeleteForumTopic(result.TopicCreatedByBot, result.RemainingInTopic))
        {
            try
            {
                await messenger.DeleteThreadAsync(
                    new PlatformGroup(PlatformKind.Telegram, command.ChatId.ToString(), string.Empty, null, result.ThreadId.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)),
                    ct);
                logger.LogInformation("Deleted forum topic {ThreadId} for batch {BatchId} as no sessions remained.", result.ThreadId.Value, result.GroupId);
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex, "Failed to delete forum topic {ThreadId}", result.ThreadId.Value);
            }
        }

        await messenger.AnswerInteractionAsync(
            new PlatformInteractionReply(command.CallbackQueryId, result.ReplyText!),
            ct);

        // 5. Update the /listsessions message
        var listCommand = new GmRelay.Shared.Features.Sessions.ListSessions.ListSessionsCommand(platformGroup, platformUser);
        var listResult = await listSessionsHandler.HandleAsync(listCommand, ct);

        if (listResult.Sessions.Count == 0)
        {
            try
            {
                await messenger.UpdateGroupMessageAsync(
                    scheduleMessage,
                    "📭 В этой группе нет предстоящих игр.",
                    [],
                    ct);
            }
            catch { }
            return;
        }

        var text = SessionListMessageRenderer.RenderText(listResult.Sessions);
        var actions = listResult.CanManage ? SessionListMessageRenderer.RenderActions(listResult.Sessions) : [];

        try
        {
            await messenger.UpdateGroupMessageAsync(scheduleMessage, text, actions, ct);
        }
        catch (Exception ex)
        {
            logger.LogWarning(ex, "Failed to edit list sessions message");
        }
    }
}
