import { TestBed } from '@angular/core/testing';
import { FileDownloadService } from './file-download.service';

describe('FileDownloadService', () => {
  let service: FileDownloadService;
  let clickSpy: ReturnType<typeof vi.fn>;
  let createObjectURLSpy: ReturnType<typeof vi.fn>;
  let revokeObjectURLSpy: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    service = TestBed.inject(FileDownloadService);
    clickSpy = vi.fn();
    createObjectURLSpy = vi.fn(() => 'blob:mock-url');
    revokeObjectURLSpy = vi.fn();
    vi.spyOn(URL, 'createObjectURL').mockImplementation(createObjectURLSpy as (obj: Blob | MediaSource) => string);
    vi.spyOn(URL, 'revokeObjectURL').mockImplementation(revokeObjectURLSpy as (url: string) => void);
    vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(clickSpy as () => void);
  });

  it('creates an object URL, clicks a temporary anchor with the given filename, and revokes the URL', () => {
    const blob = new Blob(['content'], { type: 'text/csv' });

    service.save(blob, 'kassenbuch.csv');

    expect(createObjectURLSpy).toHaveBeenCalledWith(blob);
    expect(clickSpy).toHaveBeenCalledTimes(1);
    expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:mock-url');
  });
});
