import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

type TranslationMap = Record<string, any>;

@Injectable()
export class I18nService {
  private translations: Map<string, TranslationMap> = new Map();
  private readonly supportedLocales = ['en', 'am', 'fr', 'om'];
  private readonly defaultLocale = 'en';

  constructor() {
    this.loadTranslations();
  }

  private loadTranslations() {
    for (const locale of this.supportedLocales) {
      const filePath = path.join(__dirname, 'translations', `${locale}.json`);
      try {
        const content = fs.readFileSync(filePath, 'utf-8');
        this.translations.set(locale, JSON.parse(content));
      } catch (err) {
        console.warn(`Failed to load translation file for locale: ${locale}`);
      }
    }
  }

  translate(key: string, locale: string = this.defaultLocale, params?: Record<string, string>): string {
    const normalizedLocale = this.normalizeLocale(locale);
    const translations = this.translations.get(normalizedLocale) || this.translations.get(this.defaultLocale);
    
    if (!translations) return key;

    const keys = key.split('.');
    let value: any = translations;
    
    for (const k of keys) {
      value = value?.[k];
      if (value === undefined) return key;
    }

    if (typeof value !== 'string') return key;

    if (params) {
      return Object.entries(params).reduce(
        (text, [param, val]) => text.replace(new RegExp(`{{${param}}}`, 'g'), val),
        value
      );
    }

    return value;
  }

  private normalizeLocale(locale: string): string {
    const normalized = locale.toLowerCase().split('-')[0];
    return this.supportedLocales.includes(normalized) ? normalized : this.defaultLocale;
  }

  getSupportedLocales(): string[] {
    return this.supportedLocales;
  }
}
