import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Router } from '@angular/router';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';

describe('authInterceptor', () => {
  let http: HttpClient;
  let httpMock: HttpTestingController;
  let authService: jasmine.SpyObj<AuthService>;
  let router: jasmine.SpyObj<Router>;

  beforeEach(() => {
    authService = jasmine.createSpyObj('AuthService', ['getToken', 'logout']);
    router = jasmine.createSpyObj('Router', ['navigate']);

    TestBed.configureTestingModule({
      providers: [
        provideHttpClient(withInterceptors([authInterceptor])),
        provideHttpClientTesting(),
        { provide: AuthService, useValue: authService },
        { provide: Router, useValue: router },
      ],
    });

    http = TestBed.inject(HttpClient);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => httpMock.verify());

  it('adds Authorization header when authenticated', () => {
    authService.getToken.and.returnValue('test-token');
    http.get('/api/v1/images').subscribe();
    const req = httpMock.expectOne('/api/v1/images');
    expect(req.request.headers.get('Authorization')).toBe('Bearer test-token');
    req.flush([]);
  });

  it('does not add Authorization header when not authenticated', () => {
    authService.getToken.and.returnValue(null);
    http.get('/api/v1/images').subscribe();
    const req = httpMock.expectOne('/api/v1/images');
    expect(req.request.headers.has('Authorization')).toBeFalse();
    req.flush([]);
  });

  it('redirects to login on 401 response', () => {
    authService.getToken.and.returnValue('test-token');
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    http.get('/api/v1/images').subscribe({ error: () => {} });
    const req = httpMock.expectOne('/api/v1/images');
    req.flush('Unauthorized', { status: 401, statusText: 'Unauthorized' });
    expect(authService.logout).toHaveBeenCalled();
    expect(router.navigate).toHaveBeenCalledWith(['/login']);
  });
});
