using System.Security.Cryptography;
using System.Text;

namespace StellaOps.Scanner.Storage.Catalog;

public static class CatalogIdFactory
{
    public static string CreateArtifactId(ArtifactDocumentType type, string digest)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(digest);
        return $"{type.ToString().ToLowerInvariant()}::{NormalizeDigest(digest)}";
    }

    public static string CreateLinkId(LinkSourceType type, string fromDigest, string artifactId)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(fromDigest);
        ArgumentException.ThrowIfNullOrWhiteSpace(artifactId);

        var input = Encoding.UTF8.GetBytes($"{type}:{NormalizeDigest(fromDigest)}:{artifactId}");
        var hash = SHA256.HashData(input);
        return Convert.ToHexString(hash).ToLowerInvariant();
    }

    public static string CreateLifecycleRuleId(string artifactId, string @class)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(artifactId);
        var normalizedClass = string.IsNullOrWhiteSpace(@class) ? "default" : @class.Trim().ToLowerInvariant();
        var payload = Encoding.UTF8.GetBytes($"{artifactId}:{normalizedClass}");
        var hash = SHA256.HashData(payload);
        return Convert.ToHexString(hash).ToLowerInvariant();
    }

    private static string NormalizeDigest(string digest)
    {
        if (!digest.Contains(':', StringComparison.Ordinal))
        {
            return $"sha256:{digest.Trim().ToLowerInvariant()}";
        }

        var parts = digest.Split(':', 2, StringSplitOptions.TrimEntries);
        return $"{parts[0].ToLowerInvariant()}:{parts[1].ToLowerInvariant()}";
    }
}
