package p.packer.models;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public record PackerFileCacheEntry(
        String relativePath,
        String mimeType,
        long size,
        long lastModified,
        String fingerprint,
        Map<String, Object> metadata,
        List<PackerDiagnostic> diagnostics) {

    public PackerFileCacheEntry {
        relativePath = normalizeRelativePath(relativePath);
        mimeType = normalizeOptional(mimeType);
        if (size < 0L) {
            throw new IllegalArgumentException("size must be non-negative");
        }
        if (lastModified < 0L) {
            throw new IllegalArgumentException("lastModified must be non-negative");
        }
        fingerprint = normalizeOptional(fingerprint);
        metadata = Map.copyOf(new LinkedHashMap<>(Objects.requireNonNull(metadata, "metadata")));
        diagnostics = List.copyOf(Objects.requireNonNull(diagnostics, "diagnostics"));
    }

    private static String normalizeRelativePath(String relativePath) {
        final String safeRelativePath = Objects.requireNonNull(relativePath, "relativePath")
                .trim()
                .replace('\\', '/');
        if (safeRelativePath.isEmpty()) {
            throw new IllegalArgumentException("relativePath must not be blank");
        }
        return safeRelativePath;
    }

    private static String normalizeOptional(String value) {
        if (value == null) {
            return null;
        }
        final String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
}
