import { jsx as _jsx } from "react/jsx-runtime";
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import { useSeoResource } from '../../views/seo/useSeoResource.js';
/**
 * Regression test for the `useSeoResource` stale-response race: when the
 * dependency (and therefore the fetcher) changes rapidly, a slow earlier
 * request that resolves AFTER a faster later one must not clobber the newer
 * result. We drive this with two deferred promises whose resolution order is
 * inverted relative to the request order.
 */
function Probe({ dep, fetcher }) {
    const { data, loading, error } = useSeoResource(fetcher, [dep]);
    return (_jsx("div", { children: _jsx("span", { "data-testid": "state", children: loading ? 'loading' : (error ?? data ?? 'empty') }) }));
}
function deferred() {
    let resolve;
    let reject;
    const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
    });
    return { promise, resolve, reject };
}
describe('useSeoResource', () => {
    it('ignores a stale (earlier) response that resolves after the latest one', async () => {
        const first = deferred();
        const second = deferred();
        // First render uses the "first" fetcher (slow), then we switch deps so the
        // hook re-runs with the "second" fetcher (fast).
        const firstFetcher = () => first.promise;
        const secondFetcher = () => second.promise;
        const { rerender } = render(_jsx(Probe, { dep: 1, fetcher: firstFetcher }));
        rerender(_jsx(Probe, { dep: 2, fetcher: secondFetcher }));
        // The newer request resolves FIRST.
        await act(async () => {
            second.resolve('NEW');
        });
        await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('NEW'));
        // The stale earlier request resolves LATER — it must be ignored.
        await act(async () => {
            first.resolve('OLD');
        });
        expect(screen.getByTestId('state').textContent).toBe('NEW');
    });
    it('surfaces fetcher errors', async () => {
        const d = deferred();
        render(_jsx(Probe, { dep: 1, fetcher: () => d.promise }));
        await act(async () => {
            d.reject(new Error('boom'));
        });
        await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('boom'));
    });
});
//# sourceMappingURL=use-seo-resource.test.js.map