import 'package:uuid/uuid.dart';
import '../../models/group_model.dart';
import '../../models/group_member_model.dart';
import '../interfaces/group_service.dart';
import '../api/api_client.dart';
import 'mock_data.dart';

class MockGroupService implements GroupService {
  final List<GroupModel> _groups = List.from(MockData.groups);
  final Map<String, List<GroupMemberModel>> _members = {
    for (final e in MockData.memberships.entries) e.key: List.from(e.value),
  };
  final _uuid = const Uuid();

  @override
  Future<List<GroupModel>> getGroups() async {
    await Future.delayed(const Duration(milliseconds: 400));
    return List.unmodifiable(_groups);
  }

  @override
  Future<GroupModel> createGroup(String name) async {
    await Future.delayed(const Duration(milliseconds: 500));

    final group = GroupModel(
      id: 'g-${_uuid.v4().substring(0, 8)}',
      name: name,
      isActive: true,
      type: GroupType.public,
    );
    _groups.add(group);
    _members[group.id] = [];
    return group;
  }

  @override
  Future<void> inviteMember(String groupId, String username) async {
    await Future.delayed(const Duration(milliseconds: 400));

    final groupIdx = _groups.indexWhere((g) => g.id == groupId);
    if (groupIdx == -1) {
      throw const ApiException(statusCode: 404, message: 'گروه یافت نشد');
    }

    final existingMembers = _members.putIfAbsent(groupId, () => []);
    final member = GroupMemberModel(
      userId: _uuid.v4().substring(0, 8),
      username: username,
      role: GroupRole.member,
    );
    existingMembers.add(member);
  }

  @override
  Future<void> removeMember(String groupId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final members = _members[groupId];
    if (members != null) {
      members.removeWhere((m) => m.userId == userId);
    }
  }

  @override
  Future<List<GroupMemberModel>> getGroupMembers(String groupId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return List.unmodifiable(_members[groupId] ?? []);
  }
}
