package org.raddatz.familienarchiv.document;

import org.springframework.stereotype.Component;

/**
 * Single source of truth for the auto-generated document title
 * {@code {index} – {dateLabel} – {location}}.
 *
 * <p>The {@code document} package owns this formula; {@code importing} consumes it
 * (see ADR for issue #726). The leading {@code index} is the document's
 * {@code originalFilename}; the date label is the honest German label produced by
 * {@link DocumentTitleFormatter} (the Java half of the #666 date-label split); the
 * trailing location is the {@code meta_location} verbatim, omitted when blank.
 */
@Component
public class DocumentTitleFactory {

    static final String SEPARATOR = " – ";

    /**
     * Composes the auto-title from the document's current state. The date segment is
     * dropped for UNKNOWN precision or a null date (the honest "no date" case); the
     * location segment is dropped when blank.
     */
    public String build(Document doc) {
        // originalFilename is NOT NULL in production; guard only so a synthetic/partial entity
        // never trips StringBuilder(null) with an opaque NPE.
        StringBuilder title = new StringBuilder(doc.getOriginalFilename() == null ? "" : doc.getOriginalFilename());
        if (doc.getDocumentDate() != null && doc.getMetaDatePrecision() != DatePrecision.UNKNOWN) {
            title.append(SEPARATOR).append(DocumentTitleFormatter.formatTitleDate(
                    doc.getDocumentDate(), doc.getMetaDatePrecision(),
                    doc.getMetaDateEnd(), doc.getMetaDateRaw()));
        }
        if (doc.getLocation() != null && !doc.getLocation().isBlank()) {
            title.append(SEPARATOR).append(doc.getLocation());
        }
        return title.toString();
    }
}
