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

namespace PARR.Core.Services.Shortcodes.Handlers;

internal class RelationshipsShortcodeHandler : IShortcodeHandler
{
    private readonly IUnitFilterService unitFilterService;

    public int Order => 70;

    private static readonly Regex _pattern = new(@"%СВЯЗИ(-ПН)?%", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    public Regex Pattern => _pattern;

    public ShortcodeDataRequirementsEnum Requirements => ShortcodeDataRequirementsEnum.Job;

    public RelationshipsShortcodeHandler(IUnitFilterService unitFilterService) => this.unitFilterService = unitFilterService;

    public async Task<string> ResolveAsync(string input, TemplateForShortcode template, string caller, CancellationToken ct = default)
    {
        if (template.Job == null) return input;

        var hasPlain = input.Contains("%СВЯЗИ%", StringComparison.OrdinalIgnoreCase);
        var hasNumbered = input.Contains("%СВЯЗИ-ПН%", StringComparison.OrdinalIgnoreCase);
        if (!hasPlain && !hasNumbered) return input;

        var relatedNames = await unitFilterService.GetRelatedUnitNamesAsync(template.JobId, template.UnitId, ct);
        var result = input;

        if (hasPlain)
            result = result.Replace("%СВЯЗИ%", string.Join("\n", relatedNames), StringComparison.OrdinalIgnoreCase);

        if (hasNumbered)
        {
            var numbered = relatedNames.Select((n, i) => $"{i + 1}. {n}");
            result = result.Replace("%СВЯЗИ-ПН%", string.Join("\n", numbered), StringComparison.OrdinalIgnoreCase);
        }

        return result;
    }
}