import { TestBed } from '@angular/core/testing';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';
import { TagService } from './tag.service';

describe('TagService', () => {
  let service: TagService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [TagService, provideHttpClient(), provideHttpClientTesting()],
    });
    service = TestBed.inject(TagService);
    httpMock = TestBed.inject(HttpTestingController);
  });

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

  it('should include q param when prefix is provided', () => {
    service.list('cat').subscribe();
    const req = httpMock.expectOne((r) => r.url === '/api/v1/tags');
    expect(req.request.params.get('q')).toBe('cat');
    req.flush({ items: [], total: 0, limit: 100, offset: 0 });
  });

  it('should omit q param when prefix is empty', () => {
    service.list().subscribe();
    const req = httpMock.expectOne((r) => r.url === '/api/v1/tags');
    expect(req.request.params.has('q')).toBeFalse();
    req.flush({ items: [], total: 0, limit: 100, offset: 0 });
  });

  it('should include sort param when provided', () => {
    service.list('', 100, 0, 'count_desc').subscribe();
    const req = httpMock.expectOne((r) => r.url === '/api/v1/tags');
    expect(req.request.params.get('sort')).toBe('count_desc');
    req.flush({ items: [], total: 0, limit: 100, offset: 0 });
  });

  it('should include min_count param when minCount is provided', () => {
    service.list('', 500, 0, 'count_desc', 1).subscribe();
    const req = httpMock.expectOne((r) => r.url === '/api/v1/tags');
    expect(req.request.params.get('min_count')).toBe('1');
    req.flush({ items: [], total: 0, limit: 500, offset: 0 });
  });

  it('should omit sort and min_count when not provided', () => {
    service.list('cat').subscribe();
    const req = httpMock.expectOne((r) => r.url === '/api/v1/tags');
    expect(req.request.params.has('sort')).toBeFalse();
    expect(req.request.params.has('min_count')).toBeFalse();
    req.flush({ items: [], total: 0, limit: 100, offset: 0 });
  });
});
