package cuisine import ( "context" "fmt" "github.com/jackc/pgx/v5/pgxpool" ) // Record is a cuisine loaded from DB with all its translations. type Record struct { Slug string Name string // English canonical name SortOrder int // Translations maps lang code to localized name. Translations map[string]string } // Records is the ordered list of cuisines, populated by LoadFromDB at startup. var Records []Record // LoadFromDB queries cuisines + cuisine_translations and populates Records. func LoadFromDB(ctx context.Context, pool *pgxpool.Pool) error { rows, err := pool.Query(ctx, ` SELECT c.slug, c.name, c.sort_order, ct.lang, ct.name FROM cuisines c LEFT JOIN cuisine_translations ct ON ct.cuisine_slug = c.slug ORDER BY c.sort_order, ct.lang`) if err != nil { return fmt.Errorf("load cuisines from db: %w", err) } defer rows.Close() bySlug := map[string]*Record{} var order []string for rows.Next() { var slug, engName string var sortOrder int var lang, name *string if err := rows.Scan(&slug, &engName, &sortOrder, &lang, &name); err != nil { return err } if _, ok := bySlug[slug]; !ok { bySlug[slug] = &Record{ Slug: slug, Name: engName, SortOrder: sortOrder, Translations: map[string]string{}, } order = append(order, slug) } if lang != nil && name != nil { bySlug[slug].Translations[*lang] = *name } } if err := rows.Err(); err != nil { return err } result := make([]Record, 0, len(order)) for _, slug := range order { result = append(result, *bySlug[slug]) } Records = result return nil } // NameFor returns the localized name for a cuisine slug. // Falls back to the English canonical name. func NameFor(slug, lang string) string { for _, c := range Records { if c.Slug == slug { if name, ok := c.Translations[lang]; ok { return name } return c.Name } } return slug }