import { describe, expect, it } from 'bun:test';
import {
  buildLinkedNoteCountByFileId,
  filterResearchFilesByIds,
  formatFileSize,
  readUploadInputs,
} from './ResearchFiles';
import type { ResearchFile } from '../../../types/research';

const file = (id: string): ResearchFile => ({
  id,
  workspaceId: 'workspace-1',
  originalName: `${id}.txt`,
  storedPath: `/tmp/${id}.txt`,
  mimeType: 'text/plain',
  sizeBytes: 1024,
  checksum: id,
  previewKind: 'text',
  createdAt: `2026-04-09T10:00:0${id.slice(-1)}Z`,
  updatedAt: `2026-04-09T10:00:0${id.slice(-1)}Z`,
});

describe('ResearchFiles utilities', () => {
  it('derives linked note counts from note file ids', () => {
    expect(
      buildLinkedNoteCountByFileId([
        { fileIds: ['file-1', 'file-2'] },
        { fileIds: ['file-1'] },
      ]),
    ).toEqual({
      'file-1': 2,
      'file-2': 1,
    });
  });

  it('filters files in requested attachment order', () => {
    expect(filterResearchFilesByIds([file('file-1'), file('file-2')], ['file-2']).map((item) => item.id)).toEqual([
      'file-2',
    ]);
  });

  it('formats file sizes compactly', () => {
    expect(formatFileSize(512)).toBe('512 B');
    expect(formatFileSize(2048)).toBe('2 KB');
  });

  it('prepares text uploads without LiteParse extraction metadata', async () => {
    const [input] = await readUploadInputs([
      new File(['hello research'], 'note.txt', { type: 'text/plain' }),
    ]);

    expect(input).toMatchObject({
      name: 'note.txt',
      mimeType: 'text/plain;charset=utf-8',
      bytes: Array.from(new TextEncoder().encode('hello research')),
    });
    expect(input?.extractedText).toBeUndefined();
    expect(input?.extractedTextSource).toBeUndefined();
  });
});
