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

@Injectable()
export class TranslationService {
  private readonly translations: Record<string, Record<string, string>>;

  constructor() {
    this.translations = this.loadTranslations();
  }

  private loadTranslations(): Record<string, Record<string, string>> {
    const translationsDir = path.join(process.cwd(), 'i18n');
    console.log("translationsDir" , translationsDir)
    const languages = ['en', 'hi'];
    const translations: Record<string, Record<string, string>> = {};

    for (const lang of languages) {
      const filePath = path.join(translationsDir, 'api-response', `${lang}.json`);
      if (fs.existsSync(filePath)) {
        try {
          const fileContent = fs.readFileSync(filePath, 'utf8');
          translations[lang] = JSON.parse(fileContent);
        } catch (error) {
          console.error(`Error loading translation file for ${lang}:`, error);
          translations[lang] = {};
        }
      } else {
        console.warn(`Translation file not found for ${lang}`);
        translations[lang] = {};
      }
    }

    return translations;
  }

  /**
   * Translates a given key to the specified language
   * @param key The translation key
   * @param lang The target language
   * @param params Optional parameters to replace in the translation
   * @returns The translated text or fallback
   */
  translate(key: string, lang: string, params?: Record<string, string>): string {
    // Validate language - if invalid, default to 'en'
    const validLang = this.isValidLanguage(lang) ? lang : 'en';
    // Check if the key exists in the target language
    let translation = '';
    if (this.translations[validLang] && this.translations[validLang][key]) {
      translation = this.translations[validLang][key];
    }
    // If key doesn't exist in target language, fallback to English
    else if (this.translations['en'] && this.translations['en'][key]) {
      translation = this.translations['en'][key];
    }
    // If key doesn't exist in English either, return the key itself
    else {
      translation = key;
    }

    // Replace parameters if provided
    if (params) {
      Object.keys(params).forEach(param => {
        translation = translation.replaceAll(`{${param}}`, params[param]);
      });
    }

    return translation;
  }

  /**
   * Validates if the provided language is supported
   * @param lang The language to validate
   * @returns Boolean indicating if language is valid
   */
  isValidLanguage(lang: string): boolean {
    return ['en', 'hi'].includes(lang);
  }

  /**
   * Gets all supported languages
   * @returns Array of supported language codes
   */
  getSupportedLanguages(): string[] {
    return ['en', 'hi'];
  }

  /**
   * Translates multiple keys at once
   * @param keys Array of translation keys
   * @param lang Target language
   * @returns Object with translated values
   */
  translateMultiple(keys: string[], lang: string): Record<string, string> {
    const result: Record<string, string> = {};
    for (const key of keys) {
      result[key] = this.translate(key, lang);
    }
    return result;
  }

  /**
   * Gets all translations for a specific language
   * @param lang The target language
   * @returns Object containing all translations for the language
   */
  getAllTranslations(lang: string): Record<string, string> {
    const validLang = this.isValidLanguage(lang) ? lang : 'en';
    return this.translations[validLang] || {};
  }
}
