namespace kehati.Helpers;
using System.Security.Cryptography;
using System.Text;
using kehati.Models.Common;
using Microsoft.EntityFrameworkCore;
public static class Custom
{
    // Ganti dengan secret Anda sendiri
    private const string Secret = "kehatiDINASLHDKI-2026";

    private static byte[] GetKey()
    {
        return MD5.HashData(Encoding.UTF8.GetBytes(Secret));
    }

    private static byte[] GetIV()
    {
        byte[] sha = SHA1.HashData(Encoding.UTF8.GetBytes(Secret));
        return sha.Take(16).ToArray();
    }

    public static string Encode(int value)
    {
        return Encode(value.ToString());
    }

    public static string Encode(string value)
    {
        string random = RandomString(4);

        string text = random + value;

        using var aes = Aes.Create();

        aes.Key = GetKey();
        aes.IV = GetIV();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        using var encryptor = aes.CreateEncryptor();

        byte[] bytes = Encoding.UTF8.GetBytes(text);

        byte[] encrypted = encryptor.TransformFinalBlock(bytes, 0, bytes.Length);

        string hex = Convert.ToHexString(encrypted).ToLower();

        return FormatUuid(hex);
    }

    public static string Decode(string value)
    {
        value = value.Replace("-", "");

        byte[] encrypted = Convert.FromHexString(value);

        using var aes = Aes.Create();

        aes.Key = GetKey();
        aes.IV = GetIV();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        using var decryptor = aes.CreateDecryptor();

        byte[] plain = decryptor.TransformFinalBlock(
            encrypted,
            0,
            encrypted.Length);

        string result = Encoding.UTF8.GetString(plain);

        // Hilangkan random 4 karakter
        return result.Substring(4);
    }

    public static int DecodeInt(string value)
    {
        return int.Parse(Decode(value));
    }

    private static string RandomString(int length)
    {
        const string chars =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        Span<byte> bytes = stackalloc byte[length];

        RandomNumberGenerator.Fill(bytes);

        var sb = new StringBuilder(length);

        foreach (byte b in bytes)
            sb.Append(chars[b % chars.Length]);

        return sb.ToString();
    }

    private static string FormatUuid(string hex)
    {
        return
            $"{hex[..8]}-" +
            $"{hex.Substring(8, 4)}-" +
            $"{hex.Substring(12, 4)}-" +
            $"{hex.Substring(16, 4)}-" +
            $"{hex.Substring(20)}";
    }

}