using System.Collections.Generic;
using Knot.Shared.Kernel;

namespace Knot.Modules.Stories.Domain;

public class StoryReaction
{
    public Guid UserId { get; set; }
    public string Emoji { get; set; } = string.Empty;
}

public class StoryReply
{
    public Guid Id { get; set; }
    public Guid UserId { get; set; }
    public string Username { get; set; } = string.Empty;
    public string DisplayName { get; set; } = string.Empty;
    public string? Avatar { get; set; }
    public string Content { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }
}

public class Story : Entity<Guid>
{
    public Guid UserId { get; private set; }
    public StoryType Type { get; private set; }
    public string? MediaUrl { get; private set; }
    public string? Content { get; private set; }
    public string? BgColor { get; private set; }
    public bool IsMuted { get; private set; }
    public DateTime CreatedAt { get; private set; }
    public int ViewsCount { get; private set; }
    public List<StoryReaction> Reactions { get; private set; } = new();
    public List<StoryReply> Replies { get; private set; } = new();

    protected Story() : base(Guid.NewGuid()) { }

    internal Story(Guid id, Guid userId, StoryType type, string? mediaUrl, string? content, string? bgColor, bool isMuted) : base(id)
    {
        UserId = userId;
        Type = type;
        MediaUrl = mediaUrl;
        Content = content;
        BgColor = bgColor;
        IsMuted = isMuted;
        CreatedAt = DateTime.UtcNow;
    }

    public static Story Create(Guid userId, StoryType type, string? mediaUrl, string? content, string? bgColor, bool isMuted = false)
    {
        return new Story(Guid.NewGuid(), userId, type, mediaUrl, content, bgColor, isMuted);
    }

    public void IncrementViewsCount()
    {
        ViewsCount++;
    }

    public void AddReaction(Guid userId, string emoji)
    {
        var existing = Reactions.FirstOrDefault(r => r.UserId == userId && r.Emoji == emoji);
        if (existing == null)
        {
            Reactions.Add(new StoryReaction { UserId = userId, Emoji = emoji });
        }
    }

    public void RemoveReaction(Guid userId, string emoji)
    {
        var reaction = Reactions.FirstOrDefault(r => r.UserId == userId && r.Emoji == emoji);
        if (reaction != null)
        {
            Reactions.Remove(reaction);
        }
    }

    public void AddReply(Guid userId, string content)
    {
        Replies.Add(new StoryReply
        {
            Id = Guid.NewGuid(),
            UserId = userId,
            Content = content,
            CreatedAt = DateTime.UtcNow
        });
    }
}
