package at.procon.dip.ingestion.mail;

import at.procon.dip.ingestion.service.MailMessageExtractionService;
import at.procon.ted.util.HashUtils;
import java.util.Locale;
import org.springframework.stereotype.Service;

@Service
public class MailImportIdentityResolver {

    public String resolveRootSourceIdentifier(MailMessageExtractionService.ParsedMailMessage parsed,
                                              MailProviderEnvelope envelope,
                                              byte[] rawMime) {
        if (envelope != null && hasText(envelope.providerMessageKey())) {
            return "mail:" + envelope.providerType().name().toLowerCase(Locale.ROOT)
                    + ":" + normalizeIdentityFragment(envelope.accountKey())
                    + ":" + normalizeIdentityFragment(envelope.folderKey())
                    + ":" + normalizeIdentityFragment(envelope.providerMessageKey());
        }
        if (hasText(parsed.messageId())) {
            return "mail:message-id:" + normalizeIdentityFragment(parsed.messageId());
        }
        return "mail:raw:" + HashUtils.computeSha256(rawMime);
    }

    public String resolveAttachmentSourceIdentifier(String rootSourceIdentifier,
                                                    MailMessageExtractionService.MailAttachment attachment) {
        if (hasText(attachment.partPath())) {
            return rootSourceIdentifier + ":part:" + normalizeIdentityFragment(attachment.partPath());
        }
        if (attachment.attachmentIndex() != null) {
            return rootSourceIdentifier + ":attachment:" + attachment.attachmentIndex();
        }
        return rootSourceIdentifier + ":attachment:"
                + normalizeIdentityFragment(attachment.fileName())
                + ":" + HashUtils.computeSha256(attachment.data());
    }

    private String normalizeIdentityFragment(String raw) {
        if (raw == null || raw.isBlank()) {
            return "_";
        }
        return raw.trim()
                .replaceAll("^<|>$", "")
                .replaceAll("\\s+", "_")
                .replaceAll("[^A-Za-z0-9._:@/+\\-]", "_");
    }

    private boolean hasText(String value) {
        return value != null && !value.isBlank();
    }
}
