import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fileAssetUrl, fileDownloadUrl, uploadFile } from '@/shared/api/files';
import { apiFormRequest, createApiUrl } from '@/shared/api/httpClient';

vi.mock('@/shared/api/httpClient', () => ({
  apiFormRequest: vi.fn(),
  createApiUrl: vi.fn((path: string) => `http://localhost:8080${path}`),
}));

describe('files API', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('uploads files through the shared HTTP form helper', async () => {
    vi.mocked(apiFormRequest).mockResolvedValueOnce(new Response(null, { status: 204 }));

    const privateUrl = await uploadFile('users', 'avatar', new File(['x'], 'My Avatar!.png'));

    expect(privateUrl).toMatch(/^users\/avatar\/\d+-My-Avatar-\.png$/);
    expect(apiFormRequest).toHaveBeenCalledWith('/file/upload/users/avatar', expect.any(FormData));
  });

  it('builds authenticated download URLs', () => {
    expect(fileDownloadUrl('users/avatar/a.png')).toBe(
      'http://localhost:8080/file/download?privateUrl=users%2Favatar%2Fa.png',
    );
    expect(createApiUrl).toHaveBeenCalled();
  });

  it('resolves uploaded private URLs and leaves public image URLs intact', () => {
    expect(fileAssetUrl('classroom-support/strategy-images/card.png')).toBe(
      'http://localhost:8080/file/download?privateUrl=classroom-support%2Fstrategy-images%2Fcard.png',
    );
    expect(fileAssetUrl('/images/card.png')).toBe('/images/card.png');
    expect(fileAssetUrl('https://cdn.example.com/card.png')).toBe('https://cdn.example.com/card.png');
  });
});
