using Microsoft.Extensions.Logging;
using PARR.Core.Services.Shortcodes.Enums;
using PARR.Core.Services.Shortcodes.Models;
using System.Text.RegularExpressions;

namespace PARR.Core.Services.Shortcodes.Handlers;

internal class StandardShortcodeHandler : IShortcodeHandler
{
    private readonly ILogger<StandardShortcodeHandler> logger;
    public int Order => 10;

    private static readonly Regex _pattern = new(@"%(?:ЭК|ТИКТАК|РАБОТА|ГРУППА_РАБОТ|ТНК|ТНК-КРАТКО|ИД)%", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    public Regex Pattern => _pattern;

    public ShortcodeDataRequirementsEnum Requirements =>
                ShortcodeDataRequirementsEnum.Job |
                ShortcodeDataRequirementsEnum.JobGroup |
                ShortcodeDataRequirementsEnum.JobTnk |
                ShortcodeDataRequirementsEnum.UnitName;

    public StandardShortcodeHandler(ILogger<StandardShortcodeHandler> logger) => this.logger = logger;

    public Task<string> ResolveAsync(string input, TemplateForShortcode template, string caller, CancellationToken ct = default)
    {
        var result = input;
        result = Replace(result, "%ЭК%", template.UnitName);
        result = Replace(result, "%ТИКТАК%", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString());
        result = Replace(result, "%ИД%", template.Id.ToString("N"));

        if (template.Job != null)
        {
            result = Replace(result, "%РАБОТА%", template.Job.WorkName);
            result = Replace(result, "%ГРУППА_РАБОТ%", template.Job.Group?.GroupName);
            result = Replace(result, "%ТНК%", template.Job.Tnk?.Name);
            result = Replace(result, "%ТНК-КРАТКО%", template.Job.Tnk?.ShortName);
        }
        return Task.FromResult(result);
    }

    private string Replace(string input, string shortcode, string? value)
    {
        if (string.IsNullOrEmpty(value)) return input;
        return input.Replace(shortcode, value, StringComparison.OrdinalIgnoreCase);
    }
}
