import '../../models/user_model.dart';
import '../interfaces/user_service.dart';
import 'api_client.dart';

/// Real API implementation.
class UserApiService implements UserService {
  final ApiClient _client;

  UserApiService(this._client);

  @override
  Future<List<UserModel>> getUsers() async {
    final List<dynamic> data = await _client.get('/admin/users');
    return data
        .map((json) => UserModel.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  @override
  Future<CreateUserResult> createUser(
    String username, {
    String? phoneNumber,
  }) async {
    final data = await _client.post('/admin/users', {
      'username': username,
      if (phoneNumber != null) 'phone_number': phoneNumber,
    });
    final user = UserModel.fromJson(data['user'] as Map<String, dynamic>);
    final secret = data['secret'] as String;
    return (user: user, secret: secret);
  }

  @override
  Future<String> resetSecret(String userId) async {
    final data = await _client.post(
      '/admin/users/$userId/reset-secret',
      {},
    );
    return data['secret'] as String;
  }

  @override
  Future<void> logoutUser(String userId) async {
    await _client.post('/admin/users/$userId/logout', {});
  }
}
