import { HttpHandlerFn, HttpRequest, HttpResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { firstValueFrom, of } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';

describe('authInterceptor', () => {
  it('attaches a bearer token to API requests', async () => {
    const authService = { getAccessToken: vi.fn().mockResolvedValue('token-123') };
    TestBed.configureTestingModule({ providers: [{ provide: AuthService, useValue: authService }] });

    const req = new HttpRequest('GET', '/api/v1/trips');
    const next = vi.fn().mockReturnValue(of(new HttpResponse())) as unknown as HttpHandlerFn;

    await firstValueFrom(TestBed.runInInjectionContext(() => authInterceptor(req, next)));

    expect(next).toHaveBeenCalledTimes(1);
    const forwarded = vi.mocked(next).mock.calls[0][0] as HttpRequest<unknown>;
    expect(forwarded.headers.get('Authorization')).toBe('Bearer token-123');
  });

  it('does not attach a token to non-API requests', async () => {
    const authService = { getAccessToken: vi.fn().mockResolvedValue('token-123') };
    TestBed.configureTestingModule({ providers: [{ provide: AuthService, useValue: authService }] });

    const req = new HttpRequest('GET', 'https://example.com/unrelated');
    const next = vi.fn().mockReturnValue(of(new HttpResponse())) as unknown as HttpHandlerFn;

    await firstValueFrom(TestBed.runInInjectionContext(() => authInterceptor(req, next)));

    expect(authService.getAccessToken).not.toHaveBeenCalled();
    const forwarded = vi.mocked(next).mock.calls[0][0] as HttpRequest<unknown>;
    expect(forwarded.headers.get('Authorization')).toBeNull();
  });
});
