import { describe, it, expect } from 'vitest';

import {
    journal_entry_filter_list,
    journal_entry_matches_search
} from '$lib/ae_journals/ae_journals_search_helpers';

describe('Journal Entry Search Filtering', () => {
    const mockEntries = [
        {
            id: '4',
            journal_entry_id: '4',
            name: 'Hidden & Disabled',
            hide: true,
            enable: false,
            tmp_sort_1: 'd'
        },
        {
            id: '3',
            journal_entry_id: '3',
            name: 'Disabled Entry',
            hide: false,
            enable: false,
            tmp_sort_1: 'c'
        },
        {
            id: '2',
            journal_entry_id: '2',
            name: 'Hidden Entry',
            hide: true,
            enable: true,
            tmp_sort_1: 'b'
        },
        {
            id: '1',
            journal_entry_id: '1',
            name: 'Normal Entry',
            summary: 'Alpha notes',
            content: 'Beta details',
            category_code: 'general',
            hide: false,
            enable: true,
            tmp_sort_1: 'a'
        }
    ];

    it('should return all entries when filters are broad', () => {
        const result = journal_entry_filter_list(mockEntries, {
            str: '',
            cat: '',
            enabled: 'all',
            hidden: 'all',
            limit: 2
        });

        expect(result?.length).toBe(4);
        expect(result?.map((entry) => entry.id)).toEqual(['4', '3', '2', '1']);
    });

    it('should filter by enabled and hidden status', () => {
        const result = journal_entry_filter_list(mockEntries, {
            str: '',
            cat: '',
            enabled: 'enabled',
            hidden: 'not_hidden',
            limit: 50
        });

        expect(result?.length).toBe(1);
        expect(result?.[0].id).toBe('1');
    });

    it('should match text across summary and content', () => {
        expect(
            journal_entry_matches_search(mockEntries[3], {
                str: 'alpha',
                cat: '',
                enabled: 'all',
                hidden: 'all'
            })
        ).toBe(true);

        expect(
            journal_entry_matches_search(mockEntries[3], {
                str: 'beta',
                cat: '',
                enabled: 'all',
                hidden: 'all'
            })
        ).toBe(true);
    });

    it('should limit text-filtered results after sorting', () => {
        const result = journal_entry_filter_list(mockEntries, {
            str: 'entry',
            cat: '',
            enabled: 'all',
            hidden: 'all',
            limit: 2
        });

        expect(result?.length).toBe(2);
        expect(result?.map((entry) => entry.id)).toEqual(['3', '2']);
    });
});
