import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:health_app/providers/chat_provider.dart';

void main() {
  test('delayed agent welcome is skipped after session reset', () async {
    final container = ProviderContainer();
    addTearDown(container.dispose);

    final notifier = container.read(chatProvider.notifier);
    notifier.triggerAgent(ActiveAgent.diet, '营养助手');
    await notifier.resetSession();

    await Future<void>.delayed(const Duration(milliseconds: 450));

    final messages = container.read(chatProvider).messages;
    expect(messages, isEmpty);
  });

  test('agent capsule inserts welcome when session is unchanged', () async {
    final container = ProviderContainer();
    addTearDown(container.dispose);

    container
        .read(chatProvider.notifier)
        .triggerAgent(ActiveAgent.diet, '营养助手');

    await Future<void>.delayed(const Duration(milliseconds: 450));

    final messages = container.read(chatProvider).messages;
    expect(messages.map((m) => m.type), contains(MessageType.agentWelcome));
    expect(container.read(chatProvider).activeAgent, ActiveAgent.diet);
  });

  test(
    'pending agent capsule ignores later taps until welcome appears',
    () async {
      final container = ProviderContainer();
      addTearDown(container.dispose);

      final notifier = container.read(chatProvider.notifier);
      notifier.triggerAgent(ActiveAgent.diet, '营养助手');
      await Future<void>.delayed(const Duration(milliseconds: 120));
      notifier.triggerAgent(ActiveAgent.medication, '药管家');

      await Future<void>.delayed(const Duration(milliseconds: 450));

      final welcomeAgents = container
          .read(chatProvider)
          .messages
          .where((m) => m.type == MessageType.agentWelcome)
          .map((m) => m.metadata?['agent'])
          .toList();

      expect(welcomeAgents, ['diet']);
      expect(container.read(chatProvider).activeAgent, ActiveAgent.diet);
    },
  );
}
