using System.Globalization;
using System.Text.RegularExpressions;

namespace ApiOPE.Services;

public sealed record DenunciaLookup(string RelativePath);

public static partial class DenunciaLookupParser
{
    public static bool TryParse(string value, out DenunciaLookup? lookup)
    {
        lookup = null;
        var trimmed = value.Trim();

        var expedienteMatch = ExpedientePattern().Match(trimmed);
        if (expedienteMatch.Success &&
            int.TryParse(expedienteMatch.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var number) &&
            int.TryParse(expedienteMatch.Groups[2].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var year) &&
            number > 0 &&
            year is >= 2000 and <= 9999)
        {
            lookup = new DenunciaLookup($"api/denuncias/{number}/{year}/gestiona-fields");
            return true;
        }

        if (int.TryParse(trimmed, NumberStyles.None, CultureInfo.InvariantCulture, out var complaintId) &&
            complaintId > 0)
        {
            lookup = new DenunciaLookup($"api/denuncias/{complaintId}/gestiona-fields");
            return true;
        }

        return false;
    }

    [GeneratedRegex(@"^(\d+)\s*/\s*(\d{4})$", RegexOptions.CultureInvariant)]
    private static partial Regex ExpedientePattern();
}
