import React from 'react';
import { describe, it, expect } from 'vitest';
import { Provider } from 'react-redux';
import { store } from '@/state/store';
import { render, waitFor } from '@testing-library/react';
import { useFetchPosts } from '@/hooks/useFetchPosts';
import { server } from '../msw/server';
import { http, HttpResponse } from 'msw';
import { addFavorites } from '@/state/features/blogSlice';

function Harness({ onReady }: { onReady: (api: ReturnType<typeof useFetchPosts>) => void }) {
  const api = useFetchPosts();
  React.useEffect(() => {
    onReady(api);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return null;
}

describe('useFetchPosts favorites — wiki canonical', () => {
  it('selects canonical by identifier across names', async () => {
    // Favorites local contains the owner entry, but canonical is newer by carol
    store.dispatch(addFavorites([{ id: 'q-blog-myblog-post-123', user: 'alice' }])) as any;

    server.use(
      // Resolve BLOG owner and settings
      http.get('/arbitrary/resources', ({ request }) => {
        const url = new URL(request.url);
        if (
          url.searchParams.get('service') === 'BLOG' &&
          url.searchParams.get('identifier') === 'q-blog-myblog'
        ) {
          return HttpResponse.json([{ name: 'alice', identifier: 'q-blog-myblog' }]);
        }
        return HttpResponse.json([]);
      }),
      http.get('/arbitrary/BLOG/:name/:id', ({ params }) => {
        const { name, id } = params as any;
        if (name === 'alice' && id === 'q-blog-myblog') {
          return HttpResponse.json({ wikiEnabled: true });
        }
        return HttpResponse.json({}, { status: 404 });
      }),
      // Search by identifier returns two names; carol is newer (canonical)
      http.get('/arbitrary/resources/search', ({ request }) => {
        const url = new URL(request.url);
        if (
          url.searchParams.get('service') === 'BLOG_POST' &&
          url.searchParams.get('identifier') === 'q-blog-myblog-post-123'
        ) {
          return HttpResponse.json([
            {
              name: 'alice',
              identifier: 'q-blog-myblog-post-123',
              updated: 1000,
              metadata: { title: 'Owner' },
            },
            {
              name: 'carol',
              identifier: 'q-blog-myblog-post-123',
              updated: 2000,
              metadata: { title: 'Newer' },
            },
          ]);
        }
        return HttpResponse.json([]);
      }),
      http.get('/arbitrary/BLOG_POST/:name/:id', ({ params }) => {
        return HttpResponse.json({
          title: 'Newer',
          createdAt: 1,
          postContent: [{ type: 'editor', version: 1, id: 'e1', content: [{ text: 't' }] }],
        });
      }),
    );

    let api!: ReturnType<typeof useFetchPosts>;
    render(
      <Provider store={store}>
        <Harness onReady={(a) => (api = a)} />
      </Provider>,
    );

    await api.getBlogPostsFavorites();

    await waitFor(() => {
      const favs = store.getState().blog.favorites;
      expect(favs.length).toBe(1);
      expect(favs[0].user).toBe('carol');
    });
  });
});
