// Copyright (c) 2026 EzAdmin. All rights reserved.
// Licensed under the EzAdmin Client License. See LICENSE-CLIENT.txt.

using System.Text;

namespace EzAdmin.Client
{

    public static class EzAdminCode
    {

        public const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";

        public const int Length = 8;

        public const int GroupSize = 4;

        public static string Normalise(string raw)
        {
            if (string.IsNullOrEmpty(raw))
            {
                return string.Empty;
            }

            var builder = new StringBuilder(Length);
            for (int i = 0; i < raw.Length; i++)
            {
                char c = char.ToUpperInvariant(raw[i]);

                if (c == 'O')
                {
                    continue;
                }

                if (c == ' ' || c == '-' || c == '_')
                {
                    continue;
                }

                if (Alphabet.IndexOf(c) >= 0)
                {
                    builder.Append(c);
                }
                else
                {
                    return string.Empty;
                }

                if (builder.Length > Length)
                {
                    return string.Empty;
                }
            }

            return builder.Length == Length ? builder.ToString() : string.Empty;
        }

        public static string CleanPartial(string raw)
        {
            if (string.IsNullOrEmpty(raw))
            {
                return string.Empty;
            }
            var builder = new StringBuilder(Length);
            for (int i = 0; i < raw.Length && builder.Length < Length; i++)
            {
                char c = char.ToUpperInvariant(raw[i]);
                if (Alphabet.IndexOf(c) >= 0)
                {
                    builder.Append(c);
                }
            }
            return builder.ToString();
        }

        public static bool IsComplete(string raw)
        {
            return Normalise(raw).Length == Length;
        }

        public static bool IsAllowed(char c)
        {
            return Alphabet.IndexOf(char.ToUpperInvariant(c)) >= 0;
        }

        public static string Format(string raw)
        {
            string code = Normalise(raw);
            if (code.Length != Length)
            {
                return code;
            }

            return code.Substring(0, GroupSize) + "-" + code.Substring(GroupSize);
        }
    }
}
