interface ScanData {
    distillery: string;
    bottler?: string | null;
    series?: string | null;
    age?: number | null;
    vintage?: string | null;
    cask_type?: string | null;
}

/**
 * Standardizes whisky names by combining structured metadata fields.
 * Logic: [Distillery] [Age/Vintage] [Series/Bottler] [Cask Type]
 */
export function formatWhiskyName(data: ScanData): string {
    if (!data.distillery) return '';

    // 1. Start with Distillery (Essential)
    const parts = [data.distillery.trim()];

    // 2. Add Age OR Vintage
    if (data.age) {
        parts.push(`${data.age} Year Old`);
    } else if (data.vintage) {
        // If it's already a string, check if it already contains "Vintage"
        const v = data.vintage.toString().trim();
        if (v.toLowerCase().includes('vintage')) {
            parts.push(v);
        } else {
            parts.push(`Vintage ${v}`);
        }
    }

    // 3. Add Series or Bottler
    // Avoid duplicating distillery name if it appears in the series
    const distLower = data.distillery.toLowerCase();

    if (data.series && !data.series.toLowerCase().includes(distLower)) {
        parts.push(data.series.trim());
    } else if (data.bottler && !data.bottler.toLowerCase().includes(distLower)) {
        // Only show bottler if it's likely an Independent Bottling and not the distillery
        parts.push(data.bottler.trim());
    }

    // 4. Add Cask Type
    if (data.cask_type) {
        parts.push(data.cask_type.trim());
    }

    // Join with spaces and remove double spaces
    return parts.filter(Boolean).join(" ").replace(/\s+/g, ' ').trim();
}
