import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/chat/data/tools/tool_registry.dart';

void main() {
  setUp(() {
    ToolRegistry.initialize();
  });

  group('getTool', () {
    test('returns tool definition for create_calendar_event', () {
      final tool = ToolRegistry.getTool('create_calendar_event');

      expect(tool, isNotNull);
      expect(tool!.name, 'create_calendar_event');
      expect(tool.description, isNotEmpty);
    });

    test('returns null for unknown tool', () {
      expect(ToolRegistry.getTool('unknown_tool'), isNull);
    });
  });

  group('validateArgs', () {
    test('returns error for empty args (missing title)', () {
      final result = ToolRegistry.validateArgs('create_calendar_event', {});

      expect(result.ok, false);
      expect(result.error, contains('title'));
    });

    test('returns error when missing startAt', () {
      final result = ToolRegistry.validateArgs('create_calendar_event', {
        'title': 'Test Event',
      });

      expect(result.ok, false);
      expect(result.error, contains('startAt'));
    });

    test('returns ok: true for valid args with title and startAt', () {
      final result = ToolRegistry.validateArgs('create_calendar_event', {
        'title': 'x',
        'startAt': 'x',
      });

      expect(result.ok, true);
      expect(result.error, isNull);
    });

    test('returns error for unknown tool', () {
      final result = ToolRegistry.validateArgs('unknown_tool', {});

      expect(result.ok, false);
      expect(result.error, contains('Tool not found'));
    });
  });

  group('execute', () {
    test('returns eventId on success', () async {
      final result = await ToolRegistry.execute('create_calendar_event', {
        'title': 'Test Meeting',
        'startAt': '2026-03-01T10:00:00Z',
      });

      expect(result['eventId'], isNotNull);
      expect(result['ok'], true);
      expect(result['title'], 'Test Meeting');
    });

    test('throws ToolNotFoundException for unknown tool', () async {
      expect(
        () => ToolRegistry.execute('unknown_tool', {}),
        throwsA(isA<ToolNotFoundException>()),
      );
    });

    test('includes optional fields in result', () async {
      final result = await ToolRegistry.execute('create_calendar_event', {
        'title': 'Test',
        'startAt': '2026-03-01T10:00:00Z',
        'description': 'Description',
        'location': 'Room A',
        'endAt': '2026-03-01T11:00:00Z',
      });

      expect(result['description'], 'Description');
      expect(result['location'], 'Room A');
      expect(result['endAt'], '2026-03-01T11:00:00Z');
    });
  });

  group('getAllTools', () {
    test('returns list of tool definitions', () {
      final tools = ToolRegistry.getAllTools();

      expect(tools, isNotEmpty);
      expect(tools.any((t) => t.name == 'create_calendar_event'), true);
    });
  });
}
