import enMessages from '../messages/en.json';
import deMessages from '../messages/de.json';

type Messages = typeof enMessages;
const getMessages = (locale: string): Messages => {
  return locale === 'de' ? (deMessages as any) : enMessages;
};

/**
 * Maps a translated slug to original file slug
 * @param translatedSlug - The slug from URL (translated)
 * @param locale - The current locale
 * @returns The original file slug, or input slug if no mapping exists
 */
export async function mapSlugToFileSlug(translatedSlug: string, locale: string): Promise<string> {
  const messages = getMessages(locale);
  const slugs = messages.Slugs;

  // Check pages
  if (slugs.pages && translatedSlug in slugs.pages) {
    return slugs.pages[translatedSlug as keyof typeof slugs.pages];
  }

  // Check products
  if (slugs.products && translatedSlug in slugs.products) {
    return slugs.products[translatedSlug as keyof typeof slugs.products];
  }

  // Check categories
  if (slugs.categories && translatedSlug in slugs.categories) {
    return slugs.categories[translatedSlug as keyof typeof slugs.categories];
  }

  // Return original slug if no mapping found
  return translatedSlug;
}

/**
 * Maps an original file slug to translated slug for a locale
 * @param fileSlug - The original file slug
 * @param locale - The target locale
 * @returns The translated slug, or input slug if no mapping exists
 */
export async function mapFileSlugToTranslated(fileSlug: string, locale: string): Promise<string> {
  const messages = getMessages(locale);
  const slugs = messages.Slugs;

  const sections = [slugs.pages, slugs.products, slugs.categories];

  for (const sectionData of sections) {
    if (sectionData && typeof sectionData === 'object') {
      for (const [translatedSlug, mappedSlug] of Object.entries(sectionData)) {
        if (mappedSlug === fileSlug) {
          return translatedSlug;
        }
      }
    }
  }

  // Return original slug if no mapping found
  return fileSlug;
}

/**
 * Gets all translated slugs for a section
 * @param section - The section name (pages, products, categories)
 * @param locale - The current locale
 * @returns Object mapping translated slugs to file slugs
 */
export async function getSlugMappings(
  section: 'pages' | 'products' | 'categories',
  locale: string,
): Promise<Record<string, string>> {
  const messages = getMessages(locale);
  const sectionData = messages.Slugs[section];

  if (sectionData && typeof sectionData === 'object') {
    return sectionData as Record<string, string>;
  }

  return {};
}
