using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Knot.Shared.Kernel;
using Knot.Contracts.Settings.Application.Abstractions;
using Knot.Contracts.Settings.Application.DTOs;

using Knot.Modules.Stories.Domain;

namespace Knot.Modules.Stories.Application.Stories.Commands.CreateStory;

public record CreateStoryCommand(Guid UserId, string Type, string? MediaUrl, string? Content, string? BgColor, bool IsMuted) : ICommand<Guid>;

internal sealed class CreateStoryCommandHandler : ICommandHandler<CreateStoryCommand, Guid>
{
    private readonly IStoryRepository _storyRepository;
    private readonly ISettingsService _settingsService;

    public CreateStoryCommandHandler(IStoryRepository storyRepository, ISettingsService settingsService)
    {
        _storyRepository = storyRepository;
        _settingsService = settingsService;
    }

    public async Task<Result<Guid>> Handle(CreateStoryCommand request, CancellationToken cancellationToken)
    {
        if (!Enum.TryParse<StoryType>(request.Type, true, out var parsedType))
        {
            parsedType = StoryType.Image;
        }

        // Проверка Klipy
        if (parsedType == StoryType.Klipy)
        {
            var settings = await _settingsService.GetSettingsAsync(cancellationToken);
            if (!settings.Klipy.Enabled)
            {
                return Result.Failure<Guid>(new Error("Stories.KlipyDisabled", "Klipy integration is disabled by administrator."));
            }
        }

        var story = Story.Create(
            request.UserId,
            parsedType,
            request.MediaUrl,
            request.Content,
            request.BgColor,
            request.IsMuted);

        await _storyRepository.AddAsync(story, cancellationToken);

        return Result.Success(story.Id);
    }
}
