using PARR.Core.Services.Shortcodes.Enums;
using PARR.Core.Services.Shortcodes.Models;
using PARR.Domain.Settings;
using System.Text.RegularExpressions;

namespace PARR.Core.Services.Shortcodes.Handlers;

internal class ConstantsShortcodeHandler : IShortcodeHandler
{
    private readonly SettingsFromDb settings;
    public int Order => 5;

    private static readonly Regex _pattern = new(@"%[А-ЯA-Z0-9_\-]+%", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    public Regex Pattern => _pattern;

    public ShortcodeDataRequirementsEnum Requirements => ShortcodeDataRequirementsEnum.None;

    public ConstantsShortcodeHandler(SettingsFromDb settings) => this.settings = settings;

    public Task<string> ResolveAsync(string input, TemplateForShortcode template, string caller, CancellationToken ct = default)
    {
        var result = input;
        foreach (var constant in settings.TemplateNameConstantPartsList)
        {
            var shortcode = $"%{constant.Name}%";
            if (result.Contains(shortcode, StringComparison.OrdinalIgnoreCase))
            {
                result = result.Replace(shortcode, constant.Value ?? string.Empty, StringComparison.OrdinalIgnoreCase);
            }
        }
        return Task.FromResult(result);
    }
}