using System.Text;
using DntSite.Web.Features.AppConfigs.Services.Contracts;
using DntSite.Web.Features.Backlogs.Entities;
using DntSite.Web.Features.Backlogs.Models;
using DntSite.Web.Features.Backlogs.RoutingConstants;
using DntSite.Web.Features.RssFeeds.Models;

namespace DntSite.Web.Features.Backlogs.ModelsMappings;

public static class BacklogsMappersExtensions
{
    public const string BacklogTags = $"{nameof(Backlog)}_Tags";

    private static readonly CompositeFormat ParsedPostUrlTemplate =
        CompositeFormat.Parse(BacklogsRoutingConstants.PostUrlTemplate);

    public static WhatsNewItemModel MapToWhatsNewItemModel(this Backlog item,
        string siteRootUri,
        bool showBriefDescription)
    {
        ArgumentNullException.ThrowIfNull(item);

        return new WhatsNewItemModel
        {
            User = item.User,
            AuthorName = item.User?.FriendlyName ?? item.GuestUser.UserName,
            Content = showBriefDescription ? item.Description.GetBriefDescription(charLength: 450) : item.Description,
            PublishDate = new DateTimeOffset(item.Audit.CreatedAt),
            LastUpdatedTime =
                new DateTimeOffset(item.AuditActions.Count > 0
                    ? item.AuditActions[^1].CreatedAt
                    : item.Audit.CreatedAt),
            Title = $"{WhatsNewItemType.Backlogs.Value}: {item.Title}",
            OriginalTitle = item.Title,
            Url = siteRootUri.CombineUrl(string.Format(CultureInfo.InvariantCulture, ParsedPostUrlTemplate, item.Id),
                escapeRelativeUrl: false),
            Categories = [..item.Tags.Select(x => x.Name)],
            ItemType = WhatsNewItemType.Backlogs,
            Id = item.Id,
            UserId = item.UserId,
            EntityType = item.GetType()
        };
    }

    public static Backlog MapBacklogModelToBacklog(this BacklogModel source,
        IAppAntiXssService antiXssService,
        Backlog? destination = null)
    {
        ArgumentNullException.ThrowIfNull(source);
        ArgumentNullException.ThrowIfNull(antiXssService);

        var backlog = new Backlog
        {
            Title = source.Title,
            Description = antiXssService.GetSanitizedHtml(source.Description)
        };

        if (destination is not null)
        {
            destination.Title = backlog.Title;
            destination.Description = backlog.Description;
        }

        return destination ?? backlog;
    }

    public static BacklogModel MapBacklogToBacklogModel(this Backlog source)
    {
        ArgumentNullException.ThrowIfNull(source);

        return new BacklogModel
        {
            Title = source.Title,
            Description = source.Description,
            Tags = source.Tags?.Select(tag => tag.Name).ToList() ?? []
        };
    }
}
