import { describe, it, expect } from 'vitest';
import { toBibtex, toRis } from './bib';
import type { RefMetadata } from './types';

describe('toBibtex', () => {
  it('returns "" for []', () => {
    expect(toBibtex([])).toBe('');
  });

  it('emits an @article with a first-author+year key', () => {
    const refs: RefMetadata[] = [
      {
        title: 'Attention Is All You Need',
        authors: ['Ashish Vaswani', 'Noam Shazeer'],
        year: 2017,
        source: 'Crossref',
        url: 'https://doi.org/10.x',
      },
    ];
    const out = toBibtex(refs);
    expect(out).toContain('@article{vaswani2017,');
    expect(out).toContain('title = {Attention Is All You Need}');
    expect(out).toContain('author = {Ashish Vaswani and Noam Shazeer}');
    expect(out).toContain('year = {2017}');
    expect(out).toContain('url = {https://doi.org/10.x}');
  });

  it('uses @misc and ref<index> key when no authors', () => {
    const out = toBibtex([{ title: 'A book', source: 'Open Library' }]);
    expect(out).toContain('@misc{ref0,');
    expect(out).toContain('title = {A book}');
  });

  it('omits missing fields', () => {
    const out = toBibtex([{ source: 'X' }]);
    expect(out).toContain('@misc{ref0,');
    expect(out).not.toContain('title =');
    expect(out).not.toContain('year =');
  });

  it('brace-escapes special characters in values', () => {
    const out = toBibtex([{ title: 'a {b} c', source: 'X' }]);
    expect(out).toContain('title = {a \\{b\\} c}');
  });
});

describe('toRis', () => {
  it('returns "" for []', () => {
    expect(toRis([])).toBe('');
  });

  it('emits a JOUR record with one AU line per author', () => {
    const out = toRis([
      {
        title: 'T',
        authors: ['A One', 'B Two'],
        year: 2020,
        source: 'X',
        url: 'http://u',
      },
    ]);
    expect(out).toContain('TY  - JOUR');
    expect(out).toContain('TI  - T');
    expect(out).toContain('AU  - A One');
    expect(out).toContain('AU  - B Two');
    expect(out).toContain('PY  - 2020');
    expect(out).toContain('UR  - http://u');
    expect(out.split('\n')).toContain('ER  - ');
  });

  it('uses GEN and omits missing fields', () => {
    const out = toRis([{ source: 'X' }]);
    expect(out).toContain('TY  - GEN');
    expect(out).not.toContain('TI  -');
    expect(out).not.toContain('AU  -');
    expect(out).toContain('ER  - ');
  });
});
