package at.procon.dip.domain.ted.service;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Resolves a TED daily package identifier (YYYYSSSSS) from legacy source metadata.
 */
@Component
public class TedPackageIdentifierResolver {

    private static final Pattern PACKAGE_IDENTIFIER_PATTERN = Pattern.compile("(?<!\\d)(20\\d{7})(?!\\d)");

    public Optional<String> resolveFromSourceMetadata(String sourcePath, String sourceFilename) {
        return resolve(sourcePath).or(() -> resolve(sourceFilename));
    }

    public Optional<String> resolve(String value) {
        if (!StringUtils.hasText(value)) {
            return Optional.empty();
        }
        Matcher matcher = PACKAGE_IDENTIFIER_PATTERN.matcher(value);
        if (matcher.find()) {
            return Optional.of(matcher.group(1));
        }
        return Optional.empty();
    }
}
