import { describe, expect, it } from 'vitest';
import { buildReservationSearchValue, frDate } from './reservation-search';

describe('frDate', () => {
    it('formats ISO dates as d/m/Y', () => {
        expect(frDate('2026-07-20')).toBe('20/07/2026');
        expect(frDate('2026-08-03T00:00:00Z')).toBe('03/08/2026');
    });

    it('returns empty string for null / undefined / empty', () => {
        expect(frDate(null)).toBe('');
        expect(frDate(undefined)).toBe('');
        expect(frDate('')).toBe('');
    });

    it('passes through values without three date parts', () => {
        expect(frDate('foo')).toBe('foo');
    });
});

describe('buildReservationSearchValue', () => {
    const item = {
        name: '#146244863 — Mangaet Grégoire',
        property_name: 'Dar Sophia | Villa 6BR - Sea View - Sidi Bou Said',
        date_from: '2026-07-20',
        date_to: '2026-08-03',
    };

    // SearchableSelect builds its haystack from `name + internal_name +
    // searchValue` (lowercased) and matches with `includes`. Reservation items
    // carry no internal_name, so searchValue must cover everything searchable.
    const matches = (query: string) =>
        `${item.name}  ${buildReservationSearchValue(item)}`
            .toLowerCase()
            .includes(query.trim().toLowerCase());

    it('is findable by property name — the original bug', () => {
        expect(matches('Dar Sophia')).toBe(true);
        expect(matches('sidi bou')).toBe(true);
        expect(matches('villa 6br')).toBe(true);
    });

    it('is findable by contract number and client name', () => {
        expect(matches('146244863')).toBe(true);
        expect(matches('Mangaet')).toBe(true);
        expect(matches('grégoire')).toBe(true);
    });

    it('is findable by check-in date in both ISO and French formats', () => {
        expect(matches('2026-07-20')).toBe(true);
        expect(matches('20/07/2026')).toBe(true);
        expect(matches('03/08/2026')).toBe(true);
    });

    it('does not match unrelated text', () => {
        expect(matches('Dar Inexistante')).toBe(false);
    });

    it('omits missing fields without leaving "undefined"/"null" in the haystack', () => {
        const sparse = buildReservationSearchValue({ name: '#1 — X' });
        expect(sparse).toBe('#1 — X');
        expect(sparse).not.toContain('undefined');
        expect(sparse).not.toContain('null');
    });
});
