import { describe, expect, it } from 'vitest';
import { sortDocumentsByDate } from './sort';

const doc = (id: string, documentDate: string | null) =>
	({ id, documentDate }) as { id: string; documentDate: string | null };

describe('sortDocumentsByDate', () => {
	it('sorts DESC by default — newest first', () => {
		const docs = [doc('a', '1920-01-01'), doc('b', '1950-06-15'), doc('c', '1935-03-10')];
		const result = sortDocumentsByDate(docs, 'DESC');
		expect(result.map((d) => d.id)).toEqual(['b', 'c', 'a']);
	});

	it('sorts ASC — oldest first', () => {
		const docs = [doc('a', '1920-01-01'), doc('b', '1950-06-15'), doc('c', '1935-03-10')];
		const result = sortDocumentsByDate(docs, 'ASC');
		expect(result.map((d) => d.id)).toEqual(['a', 'c', 'b']);
	});

	it('places documents without a date last in DESC', () => {
		const docs = [doc('a', null), doc('b', '1940-01-01'), doc('c', null)];
		const result = sortDocumentsByDate(docs, 'DESC');
		expect(result[0].id).toBe('b');
		expect(result.slice(1).map((d) => d.id)).toContain('a');
		expect(result.slice(1).map((d) => d.id)).toContain('c');
	});

	it('places documents without a date last in ASC', () => {
		const docs = [doc('a', null), doc('b', '1940-01-01'), doc('c', null)];
		const result = sortDocumentsByDate(docs, 'ASC');
		expect(result[0].id).toBe('b');
	});

	it('does not mutate the original array', () => {
		const docs = [doc('a', '1950-01-01'), doc('b', '1920-01-01')];
		const original = [...docs];
		sortDocumentsByDate(docs, 'ASC');
		expect(docs).toEqual(original);
	});

	it('returns an empty array unchanged', () => {
		expect(sortDocumentsByDate([], 'DESC')).toEqual([]);
	});
});
