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

export const languageGuard: CanActivateFn = (route, state) => {
  const langService = inject(LanguageService);
  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 — set it and proceed
    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.createUrlTree([`/${defaultLang}${pathAfterLang}`]);
  }

  // Not a recognized language code — treat as a legacy URL without lang prefix
  return router.createUrlTree([`/${defaultLang}${state.url}`]);
};
