import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MessagingProvider } from '../provider';
import { MockAdapter } from '../adapters/mock';
import { ConversationSettings } from './conversation-settings';

function mount(adapter = new MockAdapter()) {
  render(
    <MessagingProvider adapter={adapter}>
      <ConversationSettings threadId="th_mock_2" title="Storm crew" membership="group" onClose={() => {}} />
    </MessagingProvider>,
  );
  return adapter;
}

describe('MockAdapter member management', () => {
  it('adds and removes a member, and renames', async () => {
    const a = new MockAdapter();
    await a.addMember('th_mock_2', 'pp_sofia');
    expect((await a.listMembers('th_mock_2')).some((m) => m.id === 'pp_sofia')).toBe(true);
    await a.removeMember('th_mock_2', 'pp_sofia');
    expect((await a.listMembers('th_mock_2')).some((m) => m.id === 'pp_sofia')).toBe(false);
    await a.renameConversation('th_mock_2', 'Renamed');
    expect((await a.listConversations()).find((c) => c.threadId === 'th_mock_2')?.title).toBe('Renamed');
  });
});

describe('<ConversationSettings />', () => {
  it('lists members and adds one from the directory', async () => {
    const a = mount();
    // A current member is shown.
    await screen.findByText('Dan Whitaker');
    // Add an addable person from the directory.
    const sofia = await screen.findByText('Sofia Ramirez');
    fireEvent.click(sofia);
    await waitFor(async () => {
      expect((await a.listMembers('th_mock_2')).some((m) => m.id === 'pp_sofia')).toBe(true);
    });
  });
});
