import { TestBed } from '@angular/core/testing';
import { TranslateService } from '@ngx-translate/core';
import { LanguageService } from './language.service';
import { LocalStoreConstants } from '../constants/LocalStoreConstants';

describe('LanguageService', () => {
  let translateSpy: jasmine.SpyObj<TranslateService>;

  function createService(): LanguageService {
    translateSpy = jasmine.createSpyObj<TranslateService>('TranslateService', ['use']);
    TestBed.configureTestingModule({
      providers: [{ provide: TranslateService, useValue: translateSpy }],
    });
    return TestBed.inject(LanguageService);
  }

  beforeEach(() => {
    localStorage.clear();
  });

  afterEach(() => {
    localStorage.clear();
  });

  it('uses the stored language as the initial value', () => {
    localStorage.setItem(LocalStoreConstants.LANGUAGE_KEY, 'de');
    const service = createService();

    expect(service.lang()).toBe('de');
    expect(translateSpy.use).toHaveBeenCalledWith('de');
  });

  it('use() updates the signal, the translate service and localStorage', () => {
    localStorage.setItem(LocalStoreConstants.LANGUAGE_KEY, 'en');
    const service = createService();

    service.use('de');

    expect(service.lang()).toBe('de');
    expect(translateSpy.use).toHaveBeenCalledWith('de');
    expect(localStorage.getItem(LocalStoreConstants.LANGUAGE_KEY)).toBe('de');
  });
});
