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

// Simulating the filter logic from ae_comp__journal_entry_obj_li.svelte
function filterEntries(list: any[], ae_loc: any) {
    if (!list) return null;
    return list.filter((item: any) => {
        if (!item) return false;

        const is_hidden = item.hide === true || item.hide === 1;
        const is_disabled = item.enable === false || item.enable === 0;

        // Standard Visibility: Filter out hidden/disabled if not in Edit Mode
        if (!ae_loc.edit_mode) {
            return !is_hidden && !is_disabled;
        }

        // Edit Mode Gating:
        // - To see Hidden: Must have Trusted Access or higher
        if (is_hidden && !ae_loc.trusted_access) return false;

        // - To see Disabled: Must have Administrator Access or higher
        if (is_disabled && !ae_loc.administrator_access) return false;

        return true;
    });
}

describe('Journal Entry Visibility Filtering', () => {
    const mockEntries = [
        { id: '1', name: 'Normal Entry', hide: false, enable: true },
        { id: '2', name: 'Hidden Entry', hide: true, enable: true },
        { id: '3', name: 'Disabled Entry', hide: false, enable: false },
        { id: '4', name: 'Hidden & Disabled', hide: true, enable: false },
    ];

    it('should show only normal entries when Edit Mode is OFF (Manager)', () => {
        const ae_loc = { edit_mode: false, trusted_access: true, administrator_access: true };
        const result = filterEntries(mockEntries, ae_loc);
        expect(result?.length).toBe(1);
        expect(result?.[0].id).toBe('1');
    });

    it('should show hidden entries to Trusted users when Edit Mode is ON', () => {
        const ae_loc = { edit_mode: true, trusted_access: true, administrator_access: false };
        const result = filterEntries(mockEntries, ae_loc);
        // Should see Normal (1) and Hidden (2). Should NOT see Disabled (3, 4)
        expect(result?.length).toBe(2);
        expect(result?.map(r => r.id)).toContain('1');
        expect(result?.map(r => r.id)).toContain('2');
    });

    it('should show everything to Administrators when Edit Mode is ON', () => {
        const ae_loc = { edit_mode: true, trusted_access: true, administrator_access: true };
        const result = filterEntries(mockEntries, ae_loc);
        expect(result?.length).toBe(4);
    });

    it('should hide everything sensitive to Public users even if Edit Mode is ON (Safety Check)', () => {
        const ae_loc = { edit_mode: true, trusted_access: false, administrator_access: false };
        const result = filterEntries(mockEntries, ae_loc);
        expect(result?.length).toBe(1);
        expect(result?.[0].id).toBe('1');
    });
});
