using System;

namespace StellaOps.Vexer.Core;

/// <summary>
/// Cached export artifact metadata allowing reuse of previously generated manifests.
/// </summary>
public sealed class VexCacheEntry
{
    public VexCacheEntry(
        VexQuerySignature querySignature,
        VexExportFormat format,
        VexContentAddress artifact,
        DateTimeOffset createdAt,
        long sizeBytes,
        string? manifestId = null,
        string? gridFsObjectId = null,
        DateTimeOffset? expiresAt = null)
    {
        QuerySignature = querySignature ?? throw new ArgumentNullException(nameof(querySignature));
        Artifact = artifact ?? throw new ArgumentNullException(nameof(artifact));
        Format = format;
        CreatedAt = createdAt;
        SizeBytes = sizeBytes >= 0
            ? sizeBytes
            : throw new ArgumentOutOfRangeException(nameof(sizeBytes), sizeBytes, "Size must be non-negative.");
        ManifestId = Normalize(manifestId);
        GridFsObjectId = Normalize(gridFsObjectId);

        if (expiresAt.HasValue && expiresAt.Value < createdAt)
        {
            throw new ArgumentOutOfRangeException(nameof(expiresAt), expiresAt, "Expiration cannot be before creation.");
        }

        ExpiresAt = expiresAt;
    }

    public VexQuerySignature QuerySignature { get; }

    public VexExportFormat Format { get; }

    public VexContentAddress Artifact { get; }

    public DateTimeOffset CreatedAt { get; }

    public long SizeBytes { get; }

    public string? ManifestId { get; }

    public string? GridFsObjectId { get; }

    public DateTimeOffset? ExpiresAt { get; }

    private static string? Normalize(string? value)
        => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
