import { TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { LocalStorageService } from './services/local-storage/local-storage.service';
import { ModalService } from './services/modal/modal.service';

describe('AuthGuard', () => {
  let guard: AuthGuard;
  let localStorageServiceSpy: jasmine.SpyObj<LocalStorageService>;
  let routerSpy: jasmine.SpyObj<Router>;
  let loginModalServiceSpy: jasmine.SpyObj<ModalService>;

  beforeEach(() => {
    localStorageServiceSpy = jasmine.createSpyObj('LocalStorageService', [
      'getToken',
    ]);
    routerSpy = jasmine.createSpyObj('Router', ['navigate']);
    loginModalServiceSpy = jasmine.createSpyObj('LoginModalService', [
      'openModal',
    ]);

    TestBed.configureTestingModule({
      providers: [
        AuthGuard,
        { provide: LocalStorageService, useValue: localStorageServiceSpy },
        { provide: Router, useValue: routerSpy },
        { provide: ModalService, useValue: loginModalServiceSpy },
      ],
    });

    guard = TestBed.inject(AuthGuard);
  });

  it('should allow activation when token exists', () => {
    localStorageServiceSpy.getToken.and.returnValue('valid-token');
    const result = guard.canActivate();
    expect(result).toBeTrue();
  });

  it('should deny activation and trigger redirect and modal when token is missing', async () => {
    localStorageServiceSpy.getToken.and.returnValue(null);
    routerSpy.navigate.and.returnValue(Promise.resolve(true));

    const result = guard.canActivate();
    expect(result).toBeFalse();
    expect(routerSpy.navigate).toHaveBeenCalledWith(['/']);
    expect(loginModalServiceSpy.openModal).toHaveBeenCalled();
  });
});
