import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { LanguageService } from '../services/language.service';
import { TranslateService } from '../i18n/translate.service';

export const languageGuard: CanActivateFn = async (route, state) => {
  const langService = inject(LanguageService);
  const translateService = inject(TranslateService);
  const router = inject(Router);
  const lang = route.params['lang'];

  const langObj = langService.languages.find(l => l.code === lang);

  if (langObj?.enabled) {
    // Valid and enabled language — preload its translation pack (no-op for
    // already-loaded packs), then set it and proceed.
    await translateService.preloadLanguage(lang);
    langService.setLanguage(lang);
    return true;
  }

  const defaultLang = langService.currentLanguage();

  if (langObj && !langObj.enabled) {
    // Known but disabled language — redirect to default lang, keep the rest of the path
    const pathAfterLang = state.url.slice(1 + lang.length);
    return router.parseUrl(`/${defaultLang}${pathAfterLang}`);
  }

  // Not a recognized language code — treat as a legacy URL without lang prefix.
  // Use parseUrl (not createUrlTree with a single path-segment array entry) so
  // the query string/fragment on state.url are preserved as real query params
  // instead of being percent-encoded into the path segment.
  return router.parseUrl(`/${defaultLang}${state.url}`);
};
